Search code examples
pythonstringconcatenation

Concatenate strings in a list


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?


Solution

  • 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])