f-string,亦稱為格式化字符串常量(formatted string literals)况增,是Python3.6新引入的一種字符串格式化方法,該方法源于PEP 498 – Literal String Interpolation训挡,主要目的是使格式化字符串的操作更加簡便澳骤。f-string在形式上是以 f 或 F 修飾符引領(lǐng)的字符串(f'xxx' 或 F'xxx'),以大括號 {} 標(biāo)明被替換的字段澜薄;f-string在本質(zhì)上并不是字符串常量为肮,而是一個在運(yùn)行時運(yùn)算求值的表達(dá)式:
While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
(與具有恒定值的其它字符串常量不同,格式化字符串實(shí)際上是運(yùn)行時運(yùn)算求值的表達(dá)式肤京。)
—— Python Documentation
f-string在功能方面不遜于傳統(tǒng)的%-formatting語句和str.format()函數(shù)颊艳,同時性能又優(yōu)于二者,且使用起來也更加簡潔明了忘分,因此對于Python3.6及以后的版本棋枕,推薦使用f-string進(jìn)行字符串格式化。
用法
此部分內(nèi)容主要參考以下資料:
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用大括號 {} 表示被替換字段妒峦,其中直接填入替換內(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的大括號 {} 可以填入表達(dá)式或調(diào)用函數(shù)重斑,Python會求出其結(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'
引號、大括號與反斜杠
f-string大括號內(nèi)所用的引號不能和大括號外的引號定界符沖突肯骇,可根據(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"
大括號外的引號還可以使用 \ 轉(zhuǎn)義,但大括號內(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大括號外如果需要顯示大括號累盗,則應(yīng)輸入連續(xù)兩個大括號 {{ 和 }}:
>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'
上面提到寒矿,f-string大括號內(nèi)不能使用 \ 轉(zhuǎn)義,事實(shí)上不僅如此若债,f-string大括號內(nèi)根本就不允許出現(xiàn) \符相。如果確實(shí)需要 \,則應(yīng)首先將包含 \ 的內(nèi)容用一個變量表示,再在f-string大括號內(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."
lambda表達(dá)式
f-string大括號內(nèi)也可填入lambda表達(dá)式啊终,但lambda表達(dá)式的 : 會被f-string誤認(rèn)為是表達(dá)式與格式描述符之間的分隔符镜豹,為避免歧義,需要將lambda表達(dá)式置于括號 () 內(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 '
更多例子:
'f-strings’是Python的一種新的字符串格式化方法蓝牲,要使用f-strings趟脂,只需在字符串前加上f。
基本用法
name = "Tom"
age = 3
f"His name is {name}, he's {age} years old."
"His name is Tom, he's 3 years old."
實(shí)質(zhì)上例衍,把括號內(nèi)的當(dāng)作是變量即可昔期。
支持表達(dá)式
數(shù)學(xué)運(yùn)算
f'He will be { age+1 } years old next year.'
'He will be 4 years old next year.'
對象操作
spurs = {"Guard": "Parker", "Forward": "Duncan"}
f"The {len(spurs)} players are: {spurs['Guard']} the guard, and {spurs['Forward']} the forward."
'The 2 players are: Parker the guard, and Duncan the forward.'
f'Numbers from 1-10 are {[_ for _ in range(1, 11)]}'
'Numbers from 1-10 are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'
數(shù)字操作
# 小數(shù)精度
PI = 3.141592653
f"Pi is {PI:.2f}"
'Pi is 3.14'
# 進(jìn)制轉(zhuǎn)換
f'int: 31, hex: {31:x}, oct: {31:o}'
'int: 31, hex: 1f, oct: 37'
與原始字符串聯(lián)合使用(使其沒有轉(zhuǎn)義字符)
fr'hello\nworld'
'hello\\nworld'
注意事項(xiàng)
{}內(nèi)不能包含反斜杠\,但可以使用不同的引號佛玄,或使用三引號硼一。使用引號是將不再表示一個變量,而是當(dāng)作了字符串來處理梦抢。
如何插入大括號般贼?
f"{{ {10 * 8} }}"
'{ 80 }'
f"{{ 10 * 8 }}"
'{ 10 * 8 }'
使用str.format(),非數(shù)字索引將自動轉(zhuǎn)化為字符串奥吩,而f-strings則不會
"Guard is {spurs[Guard]}".format(spurs=spurs)
'Guard is Parker'
f"Guard is {spurs[Guard]}"
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
f"Guard is {spurs[Guard]}"
NameError: name 'Guard' is not defined
f"Guard is {spurs['Guard']}"
'Guard is Parker'
摘自:
原文鏈接:https://blog.csdn.net/sunxb10/article/details/81036693
原文鏈接:https://blog.csdn.net/qq_29027865/article/details/84850683