Contents
Convert List to String in Python
To convert a list of items to string in Python, we can use String.join() method.
String.join(iterator) takes an iterator like a list as an argument, and returns a string created by concatenating the items returned by iterator with the calling string as separator.
The syntax to use join() method to join items in myList with specific separator string separator_string is
separator_string.join(myList)
If any of the items in the list is/are not of type String, or cannot be converted to a String implicitly, then join() raises TypeError. To overcome this, we may use map(type, iterator) function to map all of the items to string.
The syntax to use join() and map() methods to join items in myList with specific separator string separator_string is
separator_string.join(map(str, myList))
Since we can use the above syntax to convert a list of items that belong to different datatypes, we shall use the same in the following examples.
Examples
1. Convert a list to CSV string in Python
In the following program, we take a list of strings and convert it to a string with comma as separator between them.
Python Program
items = ["apple", "banana", "cherry"]
output = ",".join(map(str, items))
print(output)
Run Code CopyOutput
apple,banana,cherry
2. Convert a list to a string with space between items in Python
In the following program, we take a list of items and convert it to a string with single space as separator between the items.
Python Program
items = ["apple", "banana", "cherry"]
output = " ".join(map(str, items))
print(output)
Run Code CopyOutput
apple banana cherry
3. Convert a list of different data types to a string in Python
In the following program, we take a list of strings and numbers, and convert it to a string.
Python Program
items = ["apple", "banana", "cherry", 20, True, 3.14]
output = ",".join(map(str, items))
print(output)
Run Code CopyOutput
apple,banana,cherry,20,True,3.14
Summary
In this Python Examples tutorial, we learned how to convert a list of items to a String