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

我可以这样写:

s += stringfromelsewhere

或者像这样:

s = []

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

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

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

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


当前回答

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

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

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

其他回答

写出这个函数

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)

在Python >= 3.6中,新的f-string是连接字符串的有效方法。

>>> name = 'some_name'
>>> number = 123
>>>
>>> f'Name is {name} and the number is {number}.'
'Name is some_name and the number is 123.'

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

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

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

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