假设我有两个变量:
>>> a = "hello"
>>> b = "world"
我可以通过两种方式连接它们;使用
+
:>>> a + b
"helloworld"
或者使用 f 字符串:
>>> f"{a}{b}"
"helloworld"
哪种方式更好或更好的做法?有人告诉我 f-string 在性能和健壮性方面是更好的做法,我想详细了解原因。
最佳答案
这有两个方面:性能和便利性。
使用 timeit
在 Python 3.8.0 中,我发现使用 f 字符串的连接始终比 +
慢,但对于较长的字符串,百分比差异很小:
>>> from timeit import timeit
>>> timeit('a + b', setup='a, b = "hello", "world"')
0.059246900000289315
>>> timeit('f"{a}{b}"', setup='a, b = "hello", "world"')
0.06997206999949412
>>> timeit('a + b', setup='a, b = "hello"*100, "world"*100')
0.10218418099975679
>>> timeit('f"{a}{b}"', setup='a, b = "hello"*100, "world"*100')
0.1108272269993904
>>> timeit('a + b', setup='a, b = "hello"*10000, "world"*10000')
2.6094200410007033
>>> timeit('f"{a}{b}"', setup='a, b = "hello"*10000, "world"*10000')
2.7300010479993944
但是,当您的输入还不是字符串时, f-string 可能会更方便一些:
>>> a, b = [1, 2, 3], True
>>> str(a) + str(b)
'[1, 2, 3]True'
>>> f'{a}{b}'
'[1, 2, 3]True'
关于python - + 与 f-string 的字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180574/