来自http://jaynes.colorado.edu/PythonIdioms.html
“将字符串构建为列表并在末尾使用 ''.join。join 是在分隔符上调用的字符串方法,而不是列表。从空字符串调用它会连接没有分隔符的片段,这是 Python 的怪癖,而不是一开始很惊讶。这很重要:用 + 构建字符串是二次时间而不是线性时间!如果你学了一个习语,就学这个。
错误:对于字符串中的 s:result += s
右:结果 = ''.join(strings)"
我不确定为什么这是真的。如果我有一些字符串我想加入它们,对我来说,将它们放在一个列表中然后调用 ''.join 对我来说并不直观更好。将它们放入列表不会产生一些开销吗?澄清...
Python 命令行:
>>> str1 = 'Not'
>>> str2 = 'Cool'
>>> str3 = ''.join([str1, ' ', str2]) #The more efficient way **A**
>>> print str3
Not Cool
>>> str3 = str1 + ' ' + str2 #The bad way **B**
>>> print str3
Not Cool
A真的是线性时间而B是二次时间吗?