Python格式化字符串f-string概覽

簡(jiǎn)介

f-string,亦稱為格式化字符串常量(formatted string literals),是Python3.6新引入的一種字符串格式化方法,該方法源于PEP 498 -- Literal String Interpolation,主要目的是使格式化字符串的操作更加簡(jiǎn)便。f-string在形式上是以 fF 修飾符引領(lǐng)的字符串(f'xxx'F'xxx'),以大括號(hào) {} 標(biāo)明被替換的字段;f-string在本質(zhì)上并不是字符串常量,而是一個(gè)在運(yùn)行時(shí)運(yùn)算求值的表達(dá)式:

While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
(與具有恒定值的其它字符串常量不同,格式化字符串實(shí)際上是運(yùn)行時(shí)運(yùn)算求值的表達(dá)式。)
—— Python Documentation

f-string在功能方面不遜于傳統(tǒng)的%-formatting語(yǔ)句str.format()函數(shù),同時(shí)性能又優(yōu)于二者,且使用起來(lái)也更加簡(jiǎn)潔明了,因此對(duì)于Python3.6及以后的版本,推薦使用f-string進(jìn)行字符串格式化。

用法

此部分內(nèi)容主要參考以下資料:

簡(jiǎn)單使用

f-string用大括號(hào) {} 表示被替換字段,其中直接填入替換內(nèi)容:

>>> name = 'Eric'
>>> f'Hello, my name is {name}'
'Hello, my name is Eric'

>>> number = 7
>>> f'My lucky number is {number}'
'My lucky number is 7'

>>> price = 19.99
>>> f'The price of this book is {price}'
'The price of this book is 19.99'

表達(dá)式求值與函數(shù)調(diào)用

f-string的大括號(hào) {} 可以填入表達(dá)式或調(diào)用函數(shù),Python會(huì)求出其結(jié)果并填入返回的字符串內(nèi):

>>> f'A total number of {24 * 8 + 4}'
'A total number of 196'

>>> f'Complex number {(2 + 2j) / (2 - 3j)}'
'Complex number (-0.15384615384615388+0.7692307692307692j)'

>>> name = 'ERIC'
>>> f'My name is {name.lower()}'
'My name is eric'

>>> import math
>>> f'The answer is {math.log(math.pi)}'
'The answer is 1.1447298858494002'

引號(hào)、大括號(hào)與反斜杠

f-string大括號(hào)內(nèi)所用的引號(hào)不能和大括號(hào)外的引號(hào)定界符沖突,可根據(jù)情況靈活切換 '"

>>> f'I am {"Eric"}'
'I am Eric'
>>> f'I am {'Eric'}'
  File "<stdin>", line 1
    f'I am {'Eric'}'
                ^
SyntaxError: invalid syntax

'" 不足以滿足要求,還可以使用 '''"""

>>> f"He said {"I'm Eric"}"
  File "<stdin>", line 1
    f"He said {"I'm Eric"}"
                ^
SyntaxError: invalid syntax

>>> f'He said {"I'm Eric"}'
  File "<stdin>", line 1
    f'He said {"I'm Eric"}'
                  ^
SyntaxError: invalid syntax

>>> f"""He said {"I'm Eric"}"""
"He said I'm Eric"
>>> f'''He said {"I'm Eric"}'''
"He said I'm Eric"

大括號(hào)外的引號(hào)還可以使用 \ 轉(zhuǎn)義,但大括號(hào)內(nèi)不能使用 \ 轉(zhuǎn)義:

>>> f'''He\'ll say {"I'm Eric"}'''
"He'll say I'm Eric"
>>> f'''He'll say {"I\'m Eric"}'''
  File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash

f-string大括號(hào)外如果需要顯示大括號(hào),則應(yīng)輸入連續(xù)兩個(gè)大括號(hào) {{}}

>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'

上面提到,f-string大括號(hào)內(nèi)不能使用 \ 轉(zhuǎn)義,事實(shí)上不僅如此,f-string大括號(hào)內(nèi)根本就不允許出現(xiàn) \。如果確實(shí)需要 \,則應(yīng)首先將包含 \ 的內(nèi)容用一個(gè)變量表示,再在f-string大括號(hào)內(nèi)填入變量名:

>>> f"newline: {ord('\n')}"
  File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash

>>> newline = ord('\n')
>>> f'newline: {newline}'
'newline: 10'

多行f-string

f-string還可用于多行字符串:

>>> name = 'Eric'
>>> age = 27
>>> f"Hello!" \
... f"I'm {name}." \
... f"I'm {age}."
"Hello!I'm Eric.I'm 27."
>>> f"""Hello!
...     I'm {name}.
...     I'm {age}."""
"Hello!\n    I'm Eric.\n    I'm 27."

自定義格式:對(duì)齊、寬度、符號(hào)、補(bǔ)零、精度、進(jìn)制等

f-string采用 {content:format} 設(shè)置字符串格式,其中 content 是替換并填入字符串的內(nèi)容,可以是變量、表達(dá)式或函數(shù)等,format 是格式描述符。采用默認(rèn)格式時(shí)不必指定 {:format},如上面例子所示只寫 {content} 即可。

關(guān)于格式描述符的詳細(xì)語(yǔ)法及含義可查閱Python官方文檔,這里按使用時(shí)的先后順序簡(jiǎn)要介紹常用格式描述符的含義與作用:

對(duì)齊相關(guān)格式描述符

格式描述符 含義與作用
< 左對(duì)齊(字符串默認(rèn)對(duì)齊方式)
> 右對(duì)齊(數(shù)值默認(rèn)對(duì)齊方式)
^ 居中

數(shù)字符號(hào)相關(guān)格式描述符

格式描述符 含義與作用
+ 負(fù)數(shù)前加負(fù)號(hào)(-),正數(shù)前加正號(hào)(+
- 負(fù)數(shù)前加負(fù)號(hào)(-),正數(shù)前不加任何符號(hào)(默認(rèn))
(空格) 負(fù)數(shù)前加負(fù)號(hào)(-),正數(shù)前加一個(gè)空格

注:僅適用于數(shù)值類型。

數(shù)字顯示方式相關(guān)格式描述符

格式描述符 含義與作用
# 切換數(shù)字顯示方式

注1:僅適用于數(shù)值類型。
注2:# 對(duì)不同數(shù)值類型的作用效果不同,詳見下表:

數(shù)值類型 不加#(默認(rèn)) # 區(qū)別
二進(jìn)制整數(shù) '1111011' '0b1111011' 開頭是否顯示 0b
八進(jìn)制整數(shù) '173' '0o173' 開頭是否顯示 0o
十進(jìn)制整數(shù) '123' '123' 無(wú)區(qū)別
十六進(jìn)制整數(shù)(小寫字母) '7b' '0x7b' 開頭是否顯示 0x
十六進(jìn)制整數(shù)(大寫字母) '7B' '0X7B' 開頭是否顯示 0X

寬度與精度相關(guān)格式描述符

格式描述符 含義與作用
width 整數(shù) width 指定寬度
0width 整數(shù) width 指定寬度,開頭的 0 指定高位用 0 補(bǔ)足寬度
width.precision 整數(shù) width 指定寬度,整數(shù) precision 指定顯示精度

注1:0width 不可用于復(fù)數(shù)類型和非數(shù)值類型,width.precision 不可用于整數(shù)類型。
注2:width.precision 用于不同格式類型的浮點(diǎn)數(shù)、復(fù)數(shù)時(shí)的含義也不同:用于 f、F、e、E% 時(shí) precision 指定的是小數(shù)點(diǎn)后的位數(shù),用于 gG 時(shí) precision 指定的是有效數(shù)字位數(shù)(小數(shù)點(diǎn)前位數(shù)+小數(shù)點(diǎn)后位數(shù))。
注3:width.precision 除浮點(diǎn)數(shù)、復(fù)數(shù)外還可用于字符串,此時(shí) precision 含義是只使用字符串中前 precision 位字符。

示例:

>>> a = 123.456
>>> f'a is {a:8.2f}'
'a is   123.46'
>>> f'a is {a:08.2f}'
'a is 00123.46'
>>> f'a is {a:8.2e}'
'a is 1.23e+02'
>>> f'a is {a:8.2%}'
'a is 12345.60%'
>>> f'a is {a:8.2g}'
'a is  1.2e+02'

>>> s = 'hello'
>>> f's is {s:8s}'
's is hello   '
>>> f's is {s:8.3s}'
's is hel     '

千位分隔符相關(guān)格式描述符

格式描述符 含義與作用
, 使用,作為千位分隔符
_ 使用_作為千位分隔符

注1:若不指定 ,_,則f-string不使用任何千位分隔符,此為默認(rèn)設(shè)置。
注2:, 僅適用于浮點(diǎn)數(shù)、復(fù)數(shù)與十進(jìn)制整數(shù):對(duì)于浮點(diǎn)數(shù)和復(fù)數(shù),, 只分隔小數(shù)點(diǎn)前的數(shù)位。
注3:_ 適用于浮點(diǎn)數(shù)、復(fù)數(shù)與二、八、十、十六進(jìn)制整數(shù):對(duì)于浮點(diǎn)數(shù)和復(fù)數(shù),_ 只分隔小數(shù)點(diǎn)前的數(shù)位;對(duì)于二、八、十六進(jìn)制整數(shù),固定從低位到高位每隔四位插入一個(gè) _(十進(jìn)制整數(shù)是每隔三位插入一個(gè) _)。

示例:

>>> a = 1234567890.098765
>>> f'a is {a:f}'
'a is 1234567890.098765'
>>> f'a is {a:,f}'
'a is 1,234,567,890.098765'
>>> f'a is {a:_f}'
'a is 1_234_567_890.098765'

>>> b = 1234567890
>>> f'b is {b:_b}'
'b is 100_1001_1001_0110_0000_0010_1101_0010'
>>> f'b is {b:_o}'
'b is 111_4540_1322'
>>> f'b is {b:_d}'
'b is 1_234_567_890'
>>> f'b is {b:_x}'
'b is 4996_02d2'

格式類型相關(guān)格式描述符

基本格式類型

格式描述符 含義與作用 適用變量類型
s 普通字符串格式 字符串
b 二進(jìn)制整數(shù)格式 整數(shù)
c 字符格式,按unicode編碼將整數(shù)轉(zhuǎn)換為對(duì)應(yīng)字符 整數(shù)
d 十進(jìn)制整數(shù)格式 整數(shù)
o 八進(jìn)制整數(shù)格式 整數(shù)
x 十六進(jìn)制整數(shù)格式(小寫字母) 整數(shù)
X 十六進(jìn)制整數(shù)格式(大寫字母) 整數(shù)
e 科學(xué)計(jì)數(shù)格式,以 e 表示 ×10^ 浮點(diǎn)數(shù)、復(fù)數(shù)、整數(shù)(自動(dòng)轉(zhuǎn)換為浮點(diǎn)數(shù))
E e 等價(jià),但以 E 表示 ×10^ 浮點(diǎn)數(shù)、復(fù)數(shù)、整數(shù)(自動(dòng)轉(zhuǎn)換為浮點(diǎn)數(shù))
f 定點(diǎn)數(shù)格式,默認(rèn)精度(precision)是6 浮點(diǎn)數(shù)、復(fù)數(shù)、整數(shù)(自動(dòng)轉(zhuǎn)換為浮點(diǎn)數(shù))
F f 等價(jià),但將 naninf 換成 NANINF 浮點(diǎn)數(shù)、復(fù)數(shù)、整數(shù)(自動(dòng)轉(zhuǎn)換為浮點(diǎn)數(shù))
g 通用格式,小數(shù)用 f,大數(shù)用 e 浮點(diǎn)數(shù)、復(fù)數(shù)、整數(shù)(自動(dòng)轉(zhuǎn)換為浮點(diǎn)數(shù))
G G 等價(jià),但小數(shù)用 F,大數(shù)用 E 浮點(diǎn)數(shù)、復(fù)數(shù)、整數(shù)(自動(dòng)轉(zhuǎn)換為浮點(diǎn)數(shù))
% 百分比格式,數(shù)字自動(dòng)乘上100后按 f 格式排版,并加 % 后綴 浮點(diǎn)數(shù)、整數(shù)(自動(dòng)轉(zhuǎn)換為浮點(diǎn)數(shù))

常用的特殊格式類型:標(biāo)準(zhǔn)庫(kù) datetime 給定的用于排版時(shí)間信息的格式類型,適用于 date、datetimetime 對(duì)象

格式描述符 含義 顯示樣例
%a 星期幾(縮寫) 'Sun'
%A 星期幾(全名) 'Sunday'
%w 星期幾(數(shù)字,0 是周日,6 是周六) '0'
%u 星期幾(數(shù)字,1 是周一,7 是周日) '7'
%d 日(數(shù)字,以 0 補(bǔ)足兩位) '07'
%b 月(縮寫) 'Aug'
%B 月(全名) 'August'
%m 月(數(shù)字,以 0 補(bǔ)足兩位) '08'
%y 年(后兩位數(shù)字,以 0 補(bǔ)足兩位) '14'
%Y 年(完整數(shù)字,不補(bǔ)零) '2014'
%H 小時(shí)(24小時(shí)制,以 0 補(bǔ)足兩位) '23'
%I 小時(shí)(12小時(shí)制,以 0 補(bǔ)足兩位) '11'
%p 上午/下午 'PM'
%M 分鐘(以 0 補(bǔ)足兩位) '23'
%S 秒鐘(以 0 補(bǔ)足兩位) '56'
%f 微秒(以 0 補(bǔ)足六位) '553777'
%z UTC偏移量(格式是 ±HHMM[SS],未指定時(shí)區(qū)則返回空字符串) '+1030'
%Z 時(shí)區(qū)名(未指定時(shí)區(qū)則返回空字符串) 'EST'
%j 一年中的第幾天(以 0 補(bǔ)足三位) '195'
%U 一年中的第幾周(以全年首個(gè)周日后的星期為第0周,以 0 補(bǔ)足兩位) '27'
%w 一年中的第幾周(以全年首個(gè)周一后的星期為第0周,以 0 補(bǔ)足兩位) '28'
%V 一年中的第幾周(以全年首個(gè)包含1月4日的星期為第1周,以 0 補(bǔ)足兩位) '28'

綜合示例

>>> a = 1234
>>> f'a is {a:^#10X}'      # 居中,寬度10位,十六進(jìn)制整數(shù)(大寫字母),顯示0X前綴
'a is   0X4D2   '

>>> b = 1234.5678
>>> f'b is {b:<+10.2f}'    # 左對(duì)齊,寬度10位,顯示正號(hào)(+),定點(diǎn)數(shù)格式,2位小數(shù)
'b is +1234.57  '

>>> c = 12345678
>>> f'c is {c:015,d}'      # 高位補(bǔ)零,寬度15位,十進(jìn)制整數(shù),使用,作為千分分割位
'c is 000,012,345,678'

>>> d = 0.5 + 2.5j
>>> f'd is {d:30.3e}'      # 寬度30位,科學(xué)計(jì)數(shù)法,3位小數(shù)
'd is           5.000e-01+2.500e+00j'

>>> import datetime
>>> e = datetime.datetime.today()
>>> f'the time is {e:%Y-%m-%d (%a) %H:%M:%S}'   # datetime時(shí)間格式
'the time is 2018-07-14 (Sat) 20:46:02'

lambda表達(dá)式

f-string大括號(hào)內(nèi)也可填入lambda表達(dá)式,但lambda表達(dá)式的 : 會(huì)被f-string誤認(rèn)為是表達(dá)式與格式描述符之間的分隔符,為避免歧義,需要將lambda表達(dá)式置于括號(hào) () 內(nèi):

>>> f'result is {lambda x: x ** 2 + 1 (2)}'
  File "<fstring>", line 1
    (lambda x)
             ^
SyntaxError: unexpected EOF while parsing

>>> f'result is {(lambda x: x ** 2 + 1) (2)}'
'result is 5'
>>> f'result is {(lambda x: x ** 2 + 1) (2):<+7.2f}'
'result is +5.00  '
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容