首页 > 解决方案 > + 与 f 字符串的字符串连接

问题描述

假设我有两个变量:

>>> a = "hello"
>>> b = "world"

我可以通过两种方式连接它们;使用+

>>> a + b
"helloworld"

或使用 f 字符串:

>>> f"{a}{b}"
"helloworld"

哪种方式更好或更好的做法?有人告诉我 f 弦在性能和鲁棒性方面是更好的做法,我想详细了解原因。

标签: pythonpython-3.xstringperformancef-string

解决方案


性能方面,我原以为格式字符串文字比字符串连接要快得多,但我震惊地发现事实并非如此。

我使用该timeit模块来测试格式化字符串文字与字符串连接所花费的时间。我测试了长度为 10 到 100 万个字符的字符串。

from timeit import timeit
import matplotlib.pyplot as plt
n = 1000000000

setup = """\
a = 'a'*{str_len}
b = 'b'*{str_len}
"""

fstr_stmt = """\
f'{a}{b}'
"""

concat_stmt = """\
a+b
"""

str_lens = [10, 100, 1000, 10000, 100000, 1000000]
fstr_t = []
concat_t = []
for str_len in str_lens:
    n_iters = n//str_len
    fstr_t.append(timeit(setup=setup.format(str_len=str_len), stmt=fstr_stmt, number=n_iters)/n_iters)
    concat_t.append(timeit(setup=setup.format(str_len=str_len), stmt=concat_stmt, number=n_iters)/n_iters)
    ratio = fstr_t[-1]/concat_t[-1]
    print(f"For two strings of length {str_len:7d}, concatenation is {ratio:.5f} times faster than f-strings")
plt.plot(str_lens, fstr_t, "r*-")
plt.plot(str_lens, concat_t, "c*-")
plt.xscale("log")
plt.yscale("log")
plt.xlabel("String length (log scale)")
plt.ylabel("Seconds per iteration (log scale)")
plt.grid()
plt.show()

控制台输出:

For two strings of length      10, concatenation is 1.06938 times faster than f-strings
For two strings of length     100, concatenation is 1.14887 times faster than f-strings
For two strings of length    1000, concatenation is 1.13994 times faster than f-strings
For two strings of length   10000, concatenation is 1.26934 times faster than f-strings
For two strings of length  100000, concatenation is 1.21585 times faster than f-strings
For two strings of length 1000000, concatenation is 1.01816 times faster than f-strings

和情节:

结果

摘要: 使用字符串连接运算符比使用格式字符串文字稍快。除非您正在执行数十万个字符串连接并且需要非常快速地完成它们,否则选择的实现不太可能产生影响。

从可读性的角度来看,f 字符串文字比字符串连接更美观且更易于阅读。此外,正如 Daniel 的回答所指出的那样,f-strings 能够处理不同类型的输入,同时使用+要求两个对象都是字符串(或__add__, 和__radd__方法的重载)。

编辑:正如 chepner 在他们的评论中指出的那样,当涉及两个以上的字符串时,使用 f-strings有效。例如,将另一个变量 , 添加c到 setup 和timeitstatements 会产生以下控制台输出:

For three strings of length      10, concatenation is 0.77931 times faster than f-strings
For three strings of length     100, concatenation is 0.67699 times faster than f-strings
For three strings of length    1000, concatenation is 0.60220 times faster than f-strings
For three strings of length   10000, concatenation is 1.27484 times faster than f-strings
For three strings of length  100000, concatenation is 0.98911 times faster than f-strings
For three strings of length 1000000, concatenation is 0.60201 times faster than f-strings

推荐阅读