Contents
Convert List to String
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
Convert List to String with Comma as Separator
In the following program, we take a list of strings and convert it to a string.
Python Program
items = ["apple", "banana", "cherry"]
output = ",".join(map(str, items))
print(output)
Run Output
apple,banana,cherry
Convert List to String with Space as Separator
In the following program, we take a list of items and convert it to a string with single space as separator.
Python Program
items = ["apple", "banana", "cherry"]
output = " ".join(map(str, items))
print(output)
Run Output
apple banana cherry
Convert List of Items belonging to Different Datatypes to String
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 Output
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
Related Tutorials
- How to Insert Item at Specific Index in Python List?
- How to Access List Items in Python?
- Python – Get Index or Position of Item in List
- Python – Check if Element is in List
- Python – Traverse List except Last Element
- How to Get List of all Files in Directory and Sub-directories?
- Shuffle Python List
- Python List with First N Elements
- Python – Check if List Contains all Elements of Another List
- Python Program to Find Smallest Number in List