<p>如果要连接许多值,则两者都不需要。附加一份清单是很贵的。你可以用StringIO来做。尤其是当你在大量的操作中积累起来的时候。</p>
<pre><code>from cStringIO import StringIO
# python3: from io import StringIO
buf = StringIO()
buf.write('foo')
buf.write('foo')
buf.write('foo')
buf.getvalue()
# 'foofoofoo'
</code></pre>
<p>如果您已经从其他操作返回了完整的列表,那么只需使用<code>''.join(aList)</code></p>
<p>来自python常见问题解答:<a href="http://docs.python.org/py3k/faq/programming.html#what-is-the-most-efficient-way-to-concatenate-many-strings-together" rel="noreferrer">What is the most efficient way to concatenate many strings together?</a></p>
<blockquote>
<p>str and bytes objects are immutable, therefore concatenating many
strings together is inefficient as each concatenation creates a new
object. In the general case, the total runtime cost is quadratic in
the total string length.</p>
<p>To accumulate many str objects, the recommended idiom is to place them
into a list and call str.join() at the end:</p>
<pre><code>chunks = []
for s in my_strings:
chunks.append(s)
result = ''.join(chunks)
</code></pre>
<p>(another reasonably efficient idiom is to use io.StringIO)</p>
<p>To accumulate many bytes objects, the recommended idiom is to extend a
bytearray object using in-place concatenation (the += operator):</p>
<pre><code>result = bytearray()
for b in my_bytes_objects:
result += b
</code></pre>
</blockquote>
<hr/>
<p><em>编辑:我很傻,结果被向后粘贴,使其看起来像是添加到列表比cStringIO快。我还添加了bytearray/str concat的测试,以及使用带有更大字符串的更大列表的第二轮测试。(python 2.7.3)</em></p>
<p><strong>ipython大型字符串列表测试示例</strong></p>
<pre><code>try:
from cStringIO import StringIO
except:
from io import StringIO
source = ['foo']*1000
%%timeit buf = StringIO()
for i in source:
buf.write(i)
final = buf.getvalue()
# 1000 loops, best of 3: 1.27 ms per loop
%%timeit out = []
for i in source:
out.append(i)
final = ''.join(out)
# 1000 loops, best of 3: 9.89 ms per loop
%%timeit out = bytearray()
for i in source:
out += i
# 10000 loops, best of 3: 98.5 µs per loop
%%timeit out = ""
for i in source:
out += i
# 10000 loops, best of 3: 161 µs per loop
## Repeat the tests with a larger list, containing
## strings that are bigger than the small string caching
## done by the Python
source = ['foo']*1000
# cStringIO
# 10 loops, best of 3: 19.2 ms per loop
# list append and join
# 100 loops, best of 3: 144 ms per loop
# bytearray() +=
# 100 loops, best of 3: 3.8 ms per loop
# str() +=
# 100 loops, best of 3: 5.11 ms per loop
</code></pre>