Python - f字串



在 3.6 版本中,Python 引入了一種新的字串格式化方法,即 f 字串字面量字串插值。使用這種格式化方法,您可以在字串常量內使用嵌入的 Python 表示式。Python f 字串速度更快、可讀性更強、更簡潔且錯誤更少。

使用 f 字串列印變數

要使用 f 字串列印變數,您只需將它們放在佔位符 ({}) 內即可。字串以 'f' 字首開頭,並在其中插入一個或多個佔位符,其值會動態填充。

示例

在下面的示例中,我們使用 f 字串列印變數。

name = 'Rajesh'
age = 23
fstring = f'My name is {name} and I am {age} years old'
print (fstring)

它將產生以下 輸出 -

My name is Rajesh and I am 23 years old

使用 f 字串計算表示式

f 字串也可用於計算 {} 佔位符內的表示式。

示例

以下示例演示瞭如何使用 f 字串計算表示式。

price = 10
quantity = 3
fstring = f'Price: {price} Quantity : {quantity} Total : {price*quantity}'
print (fstring)

它將產生以下 輸出 -

Price: 10 Quantity : 3 Total : 30

使用 f 字串列印字典鍵值對

佔位符可以由字典值填充。字典是 Python 中的內建資料型別之一,用於儲存鍵值對的無序集合。

示例

在以下示例中,我們使用 f 字串格式化字典。

user = {'name': 'Ramesh', 'age': 23}
fstring = f"My name is {user['name']} and I am {user['age']} years old"
print (fstring)

它將產生以下 輸出 -

My name is Ramesh and I am 23 years old

f 字串中的自調試表達式

在 f 字串中,= 字元用於自調試表達式,如下例所示 -

price = 10
quantity = 3
fstring = f"Total : {price*quantity=}"
print (fstring)

它將產生以下 輸出 -

Total : price*quantity=30

使用 f 字串呼叫使用者定義函式

也可以在 f 字串表示式內呼叫使用者定義的函式。為此,只需使用函式名稱並傳遞所需的引數即可。

示例

以下示例演示瞭如何在 f-string 中呼叫方法。

def total(price, quantity):
   return price*quantity

price = 10
quantity = 3

fstring = f'Price: {price} Quantity : {quantity} Total : {total(price, quantity)}'
print (fstring)

它將產生以下 輸出 -

Price: 10 Quantity : 3 Total : 30

使用 f-string 進行精度處理

Python f-string 也支援使用精度規範格式化浮點數,就像 format() 方法和字串格式化運算子 % 一樣。

name="Rajesh"
age=23
percent=55.50

fstring = f"My name is {name} and I am {age} years old and I have scored {percent:6.3f} percent marks"
print (fstring)

它將產生以下 輸出 -

My name is Rajesh and I am 23 years old and I have scored 55.500 percent marks

使用 f-string 進行字串對齊

對於字串變數,您可以指定對齊方式,就像我們在 format() 方法和格式化運算子 % 中所做的那樣。

name='TutorialsPoint'
fstring = f'Welcome To {name:>20} The largest Tutorials Library'
print (fstring)

fstring = f'Welcome To {name:<20} The largest Tutorials Library'
print (fstring)

fstring = f'Welcome To {name:^20} The largest Tutorials Library'
print (fstring)

它將產生以下 輸出 -

Welcome To       TutorialsPoint The largest Tutorials Library
Welcome To TutorialsPoint       The largest Tutorials Library
Welcome To    TutorialsPoint    The largest Tutorials Library

使用 f-string 以其他格式列印數字

當分別使用 "x"、"o" 和 "e" 時,f-string 可以顯示十六進位制、八進位制和科學計數法的數字。

示例

以下示例演示瞭如何使用 f-string 格式化數字。

num= 20
fstring = f'Hexadecimal : {num:x}'
print (fstring)

fstring = f'Octal :{num:o}'
print (fstring)

fstring = f'Scientific notation : {num:e}'
print (fstring)

它將產生以下 輸出 -

Hexadecimal : 14
Octal :24
Scientific notation : 2.000000e+01
python_string_formatting.htm
廣告