Python格式化字符串f-string f"{}{}{}"詳細介紹


簡介
f-string,亦稱為格式化字符串常量(formatted string literals),是Python3.6新引入的一種字符串格式化方法,該方法源於PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加簡便。f-string在形式上是以 f 或 F 修飾符引領的字符串(f'xxx'或 F'xxx'),以大括號 {} 標明被替換的字段;f-string在本質上並不是字符串常量,而是一個在運行時運算求值的表達式:

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

 

f-string在功能方面不遜於傳統的%-formatting語句和str.format()函數,同時性能又優於二者,且使用起來也更加簡潔明了,因此對於Python3.6及以后的版本,推薦使用f-string進行字符串格式化。

用法
此部分內容主要參考以下資料:

Python Documentation – Formatted String Literals
Python Documentation – Format String Syntax
PEP 498 – Literal String Interpolation
Python 3’s f-Strings: An Improved String Formatting Syntax (Guide)
python3 f-string格式化字符串的高級用法
Python 3: An Intro to f-strings
簡單使用
f-string用大括號 {} 表示被替換字段,其中直接填入替換內容:

>>> 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'

表達式求值與函數調用
f-string的大括號 {} 可以填入表達式或調用函數,Python會求出其結果並填入返回的字符串內:

>>> 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'


引號、大括號與反斜杠
f-string大括號內所用的引號不能和大括號外的引號定界符沖突,可根據情況靈活切換 ' 和 ":

>>> 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"

大括號外的引號還可以使用 \ 轉義,但大括號內不能使用 \ 轉義:

>>> 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大括號外如果需要顯示大括號,則應輸入連續兩個大括號 {{ 和 }}:

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


上面提到,f-string大括號內不能使用 \ 轉義,事實上不僅如此,f-string大括號內根本就不允許出現 \。如果確實需要 \,則應首先將包含 \ 的內容用一個變量表示,再在f-string大括號內填入變量名:

>>> 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."

自定義格式:對齊、寬度、符號、補零、精度、進制等
f-string采用 {content:format} 設置字符串格式,其中 content 是替換並填入字符串的內容,可以是變量、表達式或函數等,format是格式描述符。采用默認格式時不必指定 {:format},如上面例子所示只寫 {content} 即可。

關於格式描述符的詳細語法及含義可查閱Python官方文檔,這里按使用時的先后順序簡要介紹常用格式描述符的含義與作用:

 

 

 

 

注1:0width 不可用於復數類型和非數值類型,width.precision 不可用於整數類型。 
注2:width.precision 用於不同格式類型的浮點數、復數時的含義也不同:用於 f、F、e、E 和 % 時 precision 指定的是小數點后的位數,用於 g 和 G 時 precision 指定的是有效數字位數(小數點前位數+小數點后位數)。 
注3:width.precision 除浮點數、復數外還可用於字符串,此時 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 '

>>> 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'

 

 

 

 

 

 

 

 

 

>>> a = 1234
>>> f'a is {a:^#10X}'      # 居中,寬度10位,十六進制整數(大寫字母),顯示0X前綴
'a is   0X4D2   '
 
>>> b = 1234.5678
>>> f'b is {b:<+10.2f}'    # 左對齊,寬度10位,顯示正號(+),定點數格式,2位小數
'b is +1234.57  '
 
>>> c = 12345678
>>> f'c is {c:015,d}'      # 高位補零,寬度15位,十進制整數,使用,作為千分分割位
'c is 000,012,345,678'
 
>>> d = 0.5 + 2.5j
>>> f'd is {d:30.3e}'      # 寬度30位,科學計數法,3位小數
'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時間格式
'the time is 2018-07-14 (Sat) 20:46:02'
  • lambda表達式

f-string大括號內也可填入lambda表達式,但lambda表達式的 : 會被f-string誤認為是表達式與格式描述符之間的分隔符,為避免歧義,需要將lambda表達式置於括號 () 內:

>>> 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}'

 

 

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

>>> b = 1234.5678
>>> f'b is {b:<+10.2f}' # 左對齊,寬度10位,顯示正號(+),定點數格式,2位小數
'b is +1234.57 '

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

>>> d = 0.5 + 2.5j
>>> f'd is {d:30.3e}' # 寬度30位,科學計數法,3位小數
'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時間格式
'the time is 2018-07-14 (Sat) 20:46:02'
lambda表達式
f-string大括號內也可填入lambda表達式,但lambda表達式的 : 會被f-string誤認為是表達式與格式描述符之間的分隔符,為避免歧義,需要將lambda表達式置於括號 () 內:

>>> 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}'

————————————————
版權聲明:本文為CSDN博主「vitrovitro」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/yizhuanlu9607/java/article/details/89530982


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM