This tutorial shows how to convert list to string in Python with examples.
Example 1
The following Python code first generate a sample list and then use join()
to change the list to string.
# generate a sample list
list_1=['a', 'b', 'c', 'd']
# print out the sample list
print(list_1)
# change list to string
string_1 = ' '.join(list_1)
# print out the string
print(string_1)
The following is the output.
['a', 'b', 'c', 'd'] a b c d
Example 2
When a list contains elements of data type other than string, the join function can not be used directly. str()
function needs to be used to convert the other data type into a string first. The following is the example.
# generate a sample list
list_2 = [1, 2, 3, 4]
# print out the sample list
print(list_2)
# before using the join(), change each number element in a list to string first
string_2 = ' '.join([str(i) for i in list_2])
# print out the string
print(string_2)
The following is the output.
[1, 2, 3, 4] 1 2 3 4