Concatenate strings in a list

Question:

I have a list like l=['a', 'b', 'c']
I want a String like ‘abc’. So in fact the result is l[0]+l[1]+l[2], which can also be writte as

s = ''
for i in l:
    s += i

Is there any way to do this more elegantly?

Asked By: Tengis

||

Answers:

Use str.join():

s = ''.join(l)

The string on which you call this is used as the delimiter between the strings in l:

>>> l=['a', 'b', 'c']
>>> ''.join(l)
'abc'
>>> '-'.join(l)
'a-b-c'
>>> ' - spam ham and eggs - '.join(l)
'a - spam ham and eggs - b - spam ham and eggs - c'

Using str.join() is much faster than concatenating your elements one by one, as that has to create a new string object for every concatenation. str.join() only has to create one new string object.

Note that str.join() will loop over the input sequence twice. Once to calculate how big the output string needs to be, and once again to build it. As a side-effect, that means that using a list comprehension instead of a generator expression is faster:

slower_gen_expr = ' - '.join('{}: {}'.format(key, value) for key, value in some_dict)
faster_list_comp = ' - '.join(['{}: {}'.format(key, value) for key, value in some_dict])
Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.