[Tutor] working with strings in python3
steve+comp.lang.python at pearwood.info
Tue Apr 19 04:16:52 CEST 2011
On Tue, 19 Apr 2011 10:34:27 +1000, James Mills wrote:
> Normally it's considered bad practise to concatenate strings.
There's nothing wrong with concatenating (say) two or three strings.
What's a bad idea is something like:
s = ''
s += "append stuff to end"
s = ''
s = "insert stuff at beginning" + s
because that defeats the runtime optimization (CPython only!) that
*sometimes* can alleviate the badness of repeated string concatenation.
See Joel on Software for more:
But a single concatenation is more or less equally efficient as string
formatting operations (and probably more efficient, because you don't
have the overheard of parsing the format mini-language).
For repeated concatenation, the usual idiom is to collect all the
substrings in a list, then join them all at once at the end:
pieces = 
pieces.append('append stuff at end')
s = ''.join(pieces)
More information about the Python-list