f-string 句法可用於格式化字符串文字,由 CPython 3.6 引入。
f-string 采用 f 或 F 作前綴,與 + 操作內置符和 format() 方法的性能比較如下:
from datetime import datetime
start = datetime.now()
count = 2000000
while count:
count -= 1
a = "str" + "ing"
b = a + " test"
print(datetime.now() - start)
start = datetime.now()
count = 2000000
while count:
count -= 1
a = "{}ing".format("str")
b = "{} test".format(a)
print(datetime.now() - start)
start = datetime.now()
count = 2000000
while count:
count -= 1
string = "str"
a = f"{string}ing"
b = f"{a} test"
print(datetime.now() - start)
通過 數字 IDE 運行調試, 獲取以下結果。
0:00:01.061802 0:00:02.948405 0:00:01.809603
其中 + 內置操作符用時最少,但必須是 str 對象類型;f-string 句法次之,format() 最慢。
另請參閱:
版權聲明: 本文為獨傢原創稿件,版權歸 樂數軟件 ,未經許可不得轉載。