格式字符串与连接

新手上路,请多包涵

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

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

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

 path = root + '/' + output

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

原文由 wjk2a1 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 246
2 个回答

这只是为了看起来。一看就知道是什么格式。我们中的许多人更喜欢可读性而不是微优化。

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

原文由 kay 发布,翻译遵循 CC BY-SA 4.0 许可协议

我同意格式化主要用于提高可读性,但自从 3.6 中的 f-strings 发布以来,表格在性能方面发生了变化。我还认为 f 字符串更具可读性/可维护性,因为 1) 它们可以像大多数常规文本一样从左到右阅读,以及 2) 由于变量在字符串中,因此避免了连接的与间距相关的缺点。

运行这段代码:

 from timeit import timeit

runs = 1000000

def print_results(time, start_string):
    print(f'{start_string}\n'
          f'Total: {time:.4f}s\n'
          f'Avg: {(time/runs)*1000000000:.4f}ns\n')

t1 = timeit('"%s, %s" % (greeting, loc)',
            setup='greeting="hello";loc="world"',
            number=runs)
t2 = timeit('f"{greeting}, {loc}"',
            setup='greeting="hello";loc="world"',
            number=runs)
t3 = timeit('greeting + ", " + loc',
            setup='greeting="hello";loc="world"',
            number=runs)
t4 = timeit('"{}, {}".format(greeting, loc)',
            setup='greeting="hello";loc="world"',
            number=runs)

print_results(t1, '% replacement')
print_results(t2, 'f strings')
print_results(t3, 'concatenation')
print_results(t4, '.format method')

在我的机器上产生这个结果:

 % replacement
Total: 0.3044s
Avg: 304.3638ns

f strings
Total: 0.0991s
Avg: 99.0777ns

concatenation
Total: 0.1252s
Avg: 125.2442ns

.format method
Total: 0.3483s
Avg: 348.2690ns

这个答案给出了对不同问题的类似答案

原文由 Eric Ed Lohmar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题