python += 字符串连接是不好的做法吗?

Is python += string concatenation bad practice?

我正在阅读 The Hitchhiker’s Guide to Python 并且有一个简短的代码片段

foo = 'foo'
bar = 'bar'

foobar = foo + bar  # This is good
foo += 'ooo'  # This is bad, instead you should do:
foo = ''.join([foo, 'ooo'])

作者指出''.join()并不总是比+快,所以他并不反对使用+进行字符串连接。

但为什么 foo += 'ooo' 是不好的做法,而 foobar=foo+bar 被认为是好的做法?

在这段代码之前,作者写道:

One final thing to mention about strings is that using join() is not always best. In the instances where you are creating a new string from a pre-determined number of strings, using the addition operator is actually faster, but in cases like above or in cases where you are adding to an existing string, using join() should be your preferred method.

这是不好的做法吗?

可以合理地假设这个例子不是坏习惯,因为:

  • 作者没有给出任何理由。也许 him/her.
  • 不喜欢它
  • Python 文档没有提到这是不好的做法(据我所知)。
  • foo += 'ooo'foo = ''.join([foo, 'ooo']).
  • 一样可读(根据我的说法)并且快大约 100 倍

什么时候应该用一个代替另一个?

字符串连接的缺点是需要为每个连接创建一个新字符串并分配新内存!这很耗时,但对于很少且很小的字符串来说没什么大不了的。当您知道要连接的字符串数量并且不需要超过 2-4 个连接时,我会选择它。


连接字符串时 Python 只需为最终字符串分配新内存,效率更高,但计算时间可能更长。此外,由于字符串是不可变的,因此使用字符串列表来动态改变并仅在需要时将其转换为字符串通常更为实用。

使用 str.join() 创建字符串通常很方便,因为它需要一个可迭代对象。例如:

letters = ", ".join("abcdefghij")

总结

在大多数情况下,使用 str.join() 更有意义,但有时串联也同样可行。在我看来,对巨大或许多字符串使用任何形式的字符串连接都是不好的做法,就像使用 str.join() 对短而少的字符串来说是不好的做法一样。

我相信作者只是想创建一个经验法则,以便更容易地确定何时使用什么,而不会过于详细或使其复杂化。

如果字符串的数量少,并且事先知道字符串,我会去:

foo = f"{foo}ooo"

使用f-strings。但是,这仅在 python 3.6.

之后有效