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

PythonStringListConcatenation

Python Problem Overview


How do I concatenate a list of strings into a single string?

['this', 'is', 'a', 'sentence']    →    'this-is-a-sentence'

Python Solutions


Solution 1 - Python

Use str.join:

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

Solution 2 - Python

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'

Solution 3 - Python

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)'

Solution 4 - Python

Edit from the future: Please don't use the answer below. This function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.


Although @Burhan Khalid's answer is good, I think it's more understandable like this:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

The second argument to join() is optional and defaults to " ".

Solution 5 - Python

list_abc = ['aaa', 'bbb', 'ccc']

string = ''.join(list_abc)
print(string)
>>> aaabbbccc

string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc

string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc

string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc

Solution 6 - Python

We can also use Python's reduce function:

from functools import reduce

sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)

Solution 7 - Python

We can specify how we have to join the string. Instead of '-', we can use ' '

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)

Solution 8 - Python

If you want to generate a string of strings separated by commas in final result, you can use something like this:

sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"

Solution 9 - Python

If you have mixed content list. And want to stringify it. Here is one way:

Consider this list:

>>> aa
[None, 10, 'hello']

Convert it to string:

>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'

If required, convert back to list:

>>> ast.literal_eval(st)
[None, 10, 'hello']

Solution 10 - Python

def eggs(someParameter):
    del spam[3]
    someParameter.insert(3, ' and cats.')


spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)

Solution 11 - Python

Without .join() method you can use this method:

my_list=["this","is","a","sentence"]

concenated_string=""
for string in range(len(my_list)):
    if string == len(my_list)-1:
        concenated_string+=my_list[string]
    else:
        concenated_string+=f'{my_list[string]}-'
print([concenated_string])
    >>> ['this-is-a-sentence']

So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalvasView Question on Stackoverflow
Solution 1 - PythonBurhan KhalidView Answer on Stackoverflow
Solution 2 - PythonAaron SView Answer on Stackoverflow
Solution 3 - PythonWallebotView Answer on Stackoverflow
Solution 4 - PythonSilentVoidView Answer on Stackoverflow
Solution 5 - PythonmounirboulwafaView Answer on Stackoverflow
Solution 6 - PythonNishkarsh DixitView Answer on Stackoverflow
Solution 7 - PythonAbhishek VView Answer on Stackoverflow
Solution 8 - PythonCarmorenoView Answer on Stackoverflow
Solution 9 - PythonwiredcontrolView Answer on Stackoverflow
Solution 10 - PythonPyteView Answer on Stackoverflow
Solution 11 - PythonAbdulmecid PamukView Answer on Stackoverflow