Python 的 % 格式化操作符風格源自 C 語言 printf(),功能強大且直觀。
template % values
template:包含格式符的模板字串values:元組或字典,提供實際數值print("I'm %s. I'm %d years old" % ('Vamei', 99))
# 輸出:I'm Vamei. I'm 99 years old
a = "I'm %s. I'm %d years old" % ('Vamei', 99)
print(a)
print("I'm %(name)s. I'm %(age)d years old" % {'name': 'Vamei', 'age': 99})
| 符號 | 說明 |
|---|---|
%s | 字串 (str()) |
%r | 字串 (repr()) |
%c | 單一字元 |
%d/%i | 十進位整數 |
%b | 二進位整數 |
%o | 八進位整數 |
%x | 十六進位整數 |
%e/%E | 科學記號 |
%f/%F | 浮點數 |
%g/%G | 自動選擇 %e 或 %f |
%% | 字面 % 字元 |
%[(name)][flags][width].[precision]typecode
print("%+10x" % 10) # 寬度 10,右對齊,顯示正負號
print("%04d" % 5) # 寬度 4,不足補 0 → 0005
print("%6.3f" % 2.3) # 寬度 6,小數 3 位 → 2.300
print("%.*f" % (4, 1.2)) # 動態精度 → 1.2000
"{} is {}".format("bob", "14") # 位置參數
"{name} is {age}".format(name="bob", age="15") # 關鍵字參數
雖然 Python 3.6+ 推薦 f-strings,但 % 操作符相容性最好,維護舊碼時仍不可或缺。