String concatenation

Duncan Booth me at
Mon Jun 21 10:05:49 CEST 2004

Peter Hansen <peter at> wrote in news:xvydnWNN7t2X50vdRVn-
gw at

> Jonas Galvez wrote:
>> Is it true that joining the string elements of a list is faster than
>> concatenating them via the '+' operator?
> Note that there's also '%s%s%s' % ('a', 'b', 'c'), which is
> probably on par with the join technique for both performance
> and lack of readability.

A few more points.

Yes, the format string in this example isn't the clearest, but if you have 
a case where some of the strings are fixed and others vary, then the format 
string can be the clearest.


   '<a href="%s" alt="%s">%s</a>' % (uri, alt, text)

rather than:

   '<a href="'+uri+'" alt="'+alt+'">'+text+'</a>'

In many situations I find I use a combination of all three techniques. 
Build a list of strings to be concatenated to produce the final output, but 
each of these strings might be built from a format string or simple 
addition as above.

On the readability of ''.join(), I would suggest never writing it more than 
once. That means I tend to do something like:

    concatenate = ''.join


    def concatenate(*args):
        return ''.join(args)
    concatenate('a', 'b', 'c')

depending on how it is to be used.

It's also worth saying that a lot of the time you find you don't want the 
empty separator at all, (e.g. maybe newline is more appropriate), and in 
this case the join really does become easier than simple addition, but 
again it is worth wrapping it so that your intention at the point of call 
is clear.

Finally, a method call on a bare string (''.join, or '\n'.join) looks 
sufficiently bad that if, for some reason, you don't want to give it a name 
as above, I would suggest using the alternative form for calling it:

   str.join('\n', aList)

rather than:


More information about the Python-list mailing list