python - + 与 f-string 的字符串连接

标签 python python-3.x string performance f-string

假设我有两个变量:

>>> 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/

相关文章:

python - 有没有办法在找到第一个排序的 k 元素之前在 python 中对列表进行排序?

python - 如何用另一个数据框中的行减去数据框中的所有行?

c++ - 从 ‘const char*’ 到 ‘char*’ [-fpermissive] 的无效转换

javascript - jQuery如何在数组中查找字符串的一部分

python-3.x - 如何使用 Google Colab 处理本地文件?

c++ - 写入文件,编译,创建文件但不写入

python - 手动将 RGB 转换为灰度

python - 使用 Dropbox 作为我的 Django 应用程序的服务器

Python:导入子模块

python - 跨多个数据帧的逐元素平均值和标准差