Here are different ways to convert a list to string in Python. Note that if your list contains numeric data (such as integers), you’ll need to apply a different code, where you first convert each element in the list to a string (as captured in points 3 and 4 below).
(1) Convert a list that contains text to a string (with spaces among the elements):
my_list = ['aa', 'bb', 'cc', 'dd', 'ee'] my_string = ' '.join(my_list) print(my_string)
Result with spaces:
aa bb cc dd ee
(2) Convert a list that contains text to a string (without spaces):
my_list = ['aa', 'bb', 'cc', 'dd', 'ee'] my_string = ''.join(my_list) print(my_string)
Notice that in order to remove the spaces among the elements, you have to remove the space in the quotes before the “.join” in the code above.
Result without spaces:
aabbccddee
(3) Convert a list that contains numeric values to a string (with spaces among the elements):
my_list = [5, 6, 7, 12, 15] my_string = ' '.join([str(i) for i in my_list]) print(my_string)
Result with spaces:
5 6 7 12 15
(4) Convert a list that contains numeric values to a string (without spaces):
my_list = [5, 6, 7, 12, 15] my_string = ''.join([str(i) for i in my_list]) print(my_string)
Result without spaces:
5671215