Python 字串格式化 (String Formatting)

Python 提供多種字串格式化的方式,將變數或表達式插入字串中。

f-string(推薦)

Python 3.6+ 引入的 f-string 是最簡潔的格式化方式,在字串前加上 fF

name = "Alice"
age = 25

# 基本用法
print(f"My name is {name} and I am {age} years old.")
# My name is Alice and I am 25 years old.

執行表達式

a = 10
b = 20

print(f"{a} + {b} = {a + b}")  # 10 + 20 = 30
print(f"{name.upper()}")       # ALICE
print(f"{len(name)}")          # 5

呼叫函數和方法

def greet(name):
    return f"Hello, {name}!"

print(f"{greet('Bob')}")  # Hello, Bob!

items = ["apple", "banana"]
print(f"Items: {', '.join(items)}")  # Items: apple, banana

數字格式化

小數位數

pi = 3.14159265359

print(f"{pi:.2f}")   # 3.14
print(f"{pi:.4f}")   # 3.1416
print(f"{pi:.0f}")   # 3

千分位

number = 1234567890

print(f"{number:,}")    # 1,234,567,890
print(f"{number:_}")    # 1_234_567_890

百分比

ratio = 0.856

print(f"{ratio:.1%}")   # 85.6%
print(f"{ratio:.0%}")   # 86%

科學記號

big_number = 1234567890

print(f"{big_number:.2e}")  # 1.23e+09
print(f"{big_number:.4E}")  # 1.2346E+09

進制轉換

num = 255

print(f"{num:b}")   # 11111111(二進制)
print(f"{num:o}")   # 377(八進制)
print(f"{num:x}")   # ff(十六進制小寫)
print(f"{num:X}")   # FF(十六進制大寫)

對齊和填充

text = "Python"

# 靠左對齊(預設)
print(f"{text:<10}")   # "Python    "

# 靠右對齊
print(f"{text:>10}")   # "    Python"

# 置中對齊
print(f"{text:^10}")   # "  Python  "

# 指定填充字元
print(f"{text:*<10}")  # "Python****"
print(f"{text:*>10}")  # "****Python"
print(f"{text:*^10}")  # "**Python**"

數字對齊

for i in [1, 12, 123, 1234]:
    print(f"{i:>6}")

輸出:

     1
    12
   123
  1234

數字補零

num = 42

print(f"{num:05}")    # 00042
print(f"{num:08}")    # 00000042

format() 方法

name = "Alice"
age = 25

# 位置參數
print("My name is {} and I am {} years old.".format(name, age))

# 索引參數
print("{0} is {1} years old. {0} likes Python.".format(name, age))

# 關鍵字參數
print("{n} is {a} years old.".format(n=name, a=age))

格式化語法

# 小數位數
print("{:.2f}".format(3.14159))  # 3.14

# 對齊
print("{:>10}".format("hello"))  # "     hello"
print("{:<10}".format("hello"))  # "hello     "
print("{:^10}".format("hello"))  # "  hello   "

# 千分位
print("{:,}".format(1000000))    # 1,000,000

% 運算子(舊式)

name = "Alice"
age = 25

print("My name is %s and I am %d years old." % (name, age))
格式碼說明
%s字串
%d整數
%f浮點數
%x十六進制
%%百分號
print("Pi is %.2f" % 3.14159)           # Pi is 3.14
print("Hex: %x" % 255)                  # Hex: ff
print("Percentage: %.1f%%" % 85.6)      # Percentage: 85.6%
% 格式化是舊式語法,建議使用 f-string 或 format() 方法。

實際範例

表格輸出

products = [
    ("Apple", 1.50, 100),
    ("Banana", 0.75, 150),
    ("Orange", 2.00, 80)
]

print(f"{'Product':<10} {'Price':>8} {'Quantity':>10}")
print("-" * 30)

for name, price, qty in products:
    print(f"{name:<10} ${price:>7.2f} {qty:>10}")

輸出:

Product       Price   Quantity
------------------------------
Apple        $   1.50        100
Banana       $   0.75        150
Orange       $   2.00         80

日期格式化

from datetime import datetime

now = datetime.now()

print(f"{now:%Y-%m-%d}")          # 2024-12-08
print(f"{now:%Y/%m/%d %H:%M:%S}") # 2024/12/08 10:30:45
print(f"{now:%B %d, %Y}")         # December 08, 2024

Debug 輸出(Python 3.8+)

x = 10
y = 20

# 使用 = 顯示變數名稱和值
print(f"{x=}")         # x=10
print(f"{y=}")         # y=20
print(f"{x + y=}")     # x + y=30