How to concatenate items in a list to a single string? How to concatenate items in a list to a single string? python python

How to concatenate items in a list to a single string?


Use join:

>>> sentence = ['this', 'is', 'a', 'sentence']>>> '-'.join(sentence)'this-is-a-sentence'>>> ' '.join(sentence)'this is a sentence'


A more generic way to convert python lists to strings would be:

>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> my_lst_str = ''.join(map(str, my_lst))>>> print(my_lst_str)'12345678910'


It's very useful for beginners to know why join is a string method.

It's very strange at the beginning, but very useful after this.

The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).

.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).

Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.

>>> ",".join("12345").join(("(",")"))Out:'(1,2,3,4,5)'>>> list = ["(",")"]>>> ",".join("12345").join(list)Out:'(1,2,3,4,5)'