由于Python的字符串不能更改,我想知道如何更有效地连接字符串?

我可以这样写:

s += stringfromelsewhere

或者像这样:

s = []

s.append(somestring)
    
# later
    
s = ''.join(s)

在写这个问题的时候,我发现了一篇关于这个话题的好文章。

http://www.skymind.com/~ocrow/python_string/

但它在Python 2.x中。,所以问题是Python 3中有什么变化吗?


当前回答

你也可以使用这个(更有效)。(https://softwareengineering.stackexchange.com/questions/304445/why-is-s-better-than-for-concatenation)

s += "%s" %(stringfromelsewhere)

其他回答

虽然有些过时,但像Pythonista一样编程:Idiomatic Python在本节中推荐join()而不是+。就像PythonSpeedPerformanceTips在其关于字符串连接的部分中所做的那样,并附带以下免责声明:

这一节的准确性后来受到争议 Python的不同版本。在CPython 2.5中,字符串连接是公平的 虽然这可能不适用于其他Python 实现。有关讨论,请参阅ConcatenationTestCode。

推荐的方法仍然是使用追加和连接。

写出这个函数

def str_join(*args):
    return ''.join(map(str, args))

这样你就可以随时随地打电话了

str_join('Pine')  # Returns : Pine
str_join('Pine', 'apple')  # Returns : Pineapple
str_join('Pine', 'apple', 3)  # Returns : Pineapple3

你也可以使用这个(更有效)。(https://softwareengineering.stackexchange.com/questions/304445/why-is-s-better-than-for-concatenation)

s += "%s" %(stringfromelsewhere)

在稳定和交叉实现方面,通过“+”来使用字符串连接是最糟糕的连接方法,因为它不支持所有值。PEP8标准不鼓励这种做法,鼓励长期使用format()、join()和append()。

引用自链接的“编程建议”部分:

例如,不要依赖于CPython对a += b或a = a + b形式的语句的就地字符串连接的有效实现。即使在CPython中,这种优化也是脆弱的(它只对某些类型有效),并且在不使用折算的实现中根本不存在。在库的性能敏感部分,应该使用" .join()形式。这将确保跨各种实现的连接以线性时间发生。