带+和f字符串的字符串连接 [英] String concatenation with + vs. f-string
问题描述
假设我有两个变量:
>>> a = "hello"
>>> b = "world"
我可以通过两种方式将它们连接起来;使用+
:
I can concatenate them in two ways; using +
:
>>> a + b
"helloworld"
或使用f字符串:
>>> f"{a}{b}"
"helloworld"
哪种方法更好还是更好的做法?有人告诉我,f弦在性能和鲁棒性方面是更好的做法,我想详细了解为什么.
Which way is better or a better practice? Someone told me the f-string is better practice in terms of performance and robustness, and I'd like to know why in detail.
推荐答案
这有两个方面:性能和便利性.
There are two aspects to this: performance and convenience.
在Python 3.8.0中使用 timeit
,我明白了使用f字符串的连接始终比+
慢,但是对于较长的字符串,百分比差异很小:
Using timeit
in Python 3.8.0, I get that concatenation using an f-string is consistently slower than +
, but the percentage difference is small for longer strings:
>>> 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字符串可能会更方便一些:
However, the f-string may be a bit more convenient when your inputs aren't already strings:
>>> a, b = [1, 2, 3], True
>>> str(a) + str(b)
'[1, 2, 3]True'
>>> f'{a}{b}'
'[1, 2, 3]True'
这篇关于带+和f字符串的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!