格式化字符串与连接

2024-05-19 09:47:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

path = root + '/' + output

格式字符串是否有更好的性能,或者这只是为了外观?


Tags: samplepath字符串formatoutput格式root性能
3条回答

它不仅仅是为了“外观”,或者强大的词法类型转换;它也是国际化的必由之路。

您可以根据所选语言交换格式字符串。

由于在源代码中烘焙了一长串字符串连接,这实际上不可能正确执行。

与大多数情况一样,性能也会有所不同,但请扪心自问:“这是否比ns更快真的重要?”。root + '/' output方法快速且易于键入。但是当你有多个变量要打印出来的时候,这会很难快速阅读

foo = "X = " + myX + " | Y = " + someY + " Z = " + Z.toString()

foo = "X = {} | Y= {} | Z = {}".format(myX, someY, Z.toString())

哪个更容易理解发生了什么?除非你真的需要说出你的表现,否则选择最容易让人阅读和理解的方式

只是为了好看。你一眼就能看出格式是什么。我们中的许多人喜欢可读性胜过微观优化。

让我们看看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

相关问题 更多 >

    热门问题