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 = "%sing" % ("str")
    b = "%s test" % (a)
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.395206 0:00:02.948405 0:00:01.809603
其中 + 内置操作符用时最少,但必须是 str 对象类型;f-string 句法次之,format() 方法最慢。
f-string 在语法上不支持直接嵌套,如下所示:
>>> a = "string"
>>> f"{{a}}"
'{a}'
>>>
						
						可改成以下形式:
>>> a = "string"
>>> f"{chr(123)}{a}{chr(125)}"
'{string}'
>>>
						
					
					另请参阅:
版权声明: 本文为独家原创稿件,版权归 乐数软件 ,未经许可不得转载。