str.format() 的基本使用如下:
>>> print('{}網址: "{}!"'.format('菜鳥教程', 'www.runoob.com')) 菜鳥教程網址: "www.runoob.com!"
括號及其里面的字符 (稱作格式化字段) 將會被 format() 中的參數替換。
在括號中的數字用於指向傳入對象在 format() 中的位置,如下所示:
>>> print('{0} 和 {1}'.format('Google', 'Runoob')) Google 和 Runoob >>> print('{1} 和 {0}'.format('Google', 'Runoob')) Runoob 和 Google
如果在 format() 中使用了關鍵字參數, 那么它們的值會指向使用該名字的參數。
>>> print('{name}網址: {site}'.format(name='菜鳥教程', site='www.runoob.com')) 菜鳥教程網址: www.runoob.com
位置及關鍵字參數可以任意的結合:
>>> print('站點列表 {0}, {1}, 和 {other}。'.format('Google', 'Runoob', other='Taobao')) 站點列表 Google, Runoob, 和 Taobao。
'!a' (使用 ascii()), '!s' (使用 str()) 和 '!r' (使用 repr()) 可以用於在格式化某個值之前對其進行轉化:
>>> import math >>> print('常量 PI 的值近似為: {}。'.format(math.pi)) 常量 PI 的值近似為: 3.141592653589793。 >>> print('常量 PI 的值近似為: {!r}。'.format(math.pi)) 常量 PI 的值近似為: 3.141592653589793。
可選項 ':' 和格式標識符可以跟着字段名。 這就允許對值進行更好的格式化。 下面的例子將 Pi 保留到小數點后三位:
>>> import math >>> print('常量 PI 的值近似為 {0:.3f}。'.format(math.pi)) 常量 PI 的值近似為 3.142。
在 ':' 后傳入一個整數, 可以保證該域至少有這么多的寬度。 用於美化表格時很有用。
>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} >>> for name, number in table.items(): ... print('{0:10} ==> {1:10d}'.format(name, number)) ... Runoob ==> 2 Taobao ==> 3 Google ==> 1
如果你有一個很長的格式化字符串, 而你不想將它們分開, 那么在格式化時通過變量名而非位置會是很好的事情。
最簡單的就是傳入一個字典, 然后使用方括號 '[]' 來訪問鍵值 :
>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} >>> print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table)) Runoob: 2; Google: 1; Taobao: 3
也可以通過在 table 變量前使用 '**' 來實現相同的功能:
>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} >>> print('Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table)) Runoob: 2; Google: 1; Taobao: 3