gpt4 book ai didi

python - 格式化字符串与连接

转载 作者:IT老高 更新时间:2023-10-28 22:06:32 24 4
gpt4 key购买 nike

我看到很多人使用这样的格式字符串:

root = "sample"
output = "output"
path = "{}/{}".format(root, output)

而不是像这样简单地连接字符串:

path = root + '/' + output

格式字符串有更好的性能还是只是为了好看?

最佳答案

只是为了好看。您可以一眼看出格式是什么。与微优化相比,我们中的许多人更喜欢可读性。

让我们看看 IPython 的 %timeit 是怎么说的:

Python 3.7.2 (default, Jan  3 2019, 02:55:40)
IPython 5.8.0
Intel(R) Core(TM) i5-4590T CPU @ 2.00GHz

In [1]: %timeit root = "sample"; output = "output"; path = "{}/{}".format(root, output)
The slowest run took 12.44 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 5: 223 ns per loop

In [2]: %timeit root = "sample"; output = "output"; path = root + '/' + output
The slowest run took 13.82 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 5: 101 ns per loop

In [3]: %timeit root = "sample"; output = "output"; path = "%s/%s" % (root, output)
The slowest run took 27.97 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 5: 155 ns per loop

In [4]: %timeit root = "sample"; output = "output"; path = f"{root}/{output}"
The slowest run took 19.52 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 5: 77.8 ns per loop

关于python - 格式化字符串与连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38722105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com