7.1.1. 格式化的字串文本 (Formatted String Literals)
格式化的字串文本(簡稱為 f-字串),透過在字串加入前綴 f
或 F
,並將運算式編寫為 {expression}
,讓你可以在字串內加入 Python 運算式的值。
格式說明符 (format specifier) 是選擇性的,寫在運算式後面,可以更好地控制值的格式化方式。以下範例將 pi 捨入到小數點後三位:
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
在 ':'
後傳遞一個整數,可以設定該欄位至少為幾個字元寬,常用於將每一欄對齊。
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
還有一些修飾符號可以在格式化前先將值轉換過。'!a'
會套用 ascii()
,'!s'
會套用 str()
,'!r'
會套用 repr()
:
>>>>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.
=
說明符可用於將一個運算式擴充為該運算式的文字、一個等號、以及對該運算式求值 (evaluate) 後的表示法:
>>>>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
7.1.2. 字串的 format() method
str.format()
method 的基本用法如下:
>>>>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
大括號及其內的字元(稱為格式欄位)會被取代為傳遞給 str.format()
method 的物件。大括號中的數字表示該物件在傳遞給 str.format()
method 時所在的位置。
>>>>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
如果在 str.format()
method 中使用關鍵字引數,可以使用引數名稱去引用它們的值。
>>>>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
位置引數和關鍵字引數可以任意組合:
>>>>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
... other='Georg'))
The story of Bill, Manfred, and Georg.
如果你有一個不想分割的長格式化字串,比較好的方式是按名稱而不是按位置來引用變數。這項操作可以透過傳遞字典 (dict),並用方括號 '[]'
使用鍵 (key) 來輕鬆完成。
>>>>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
... 'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
用 '**' 符號,把 table
字典當作關鍵字引數來傳遞,也有一樣的結果。
>>>>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
參考文章
- https://docs.python.org/zh-tw/3/tutorial/inputoutput.html
留言
張貼留言