Javaexercise.com

How To Convert Python List to String?

This article contains examples to convert Python list to string. To convert Python List to String, we used the join() method of string class. This method returns a string after joining all the elements of the list into a single string. We can pass a separator to this method to create a string accordingly. Let's see the examples.

Example: Create String from List in Python 

See, we used the join() method to get a string from the list.

# Example to Convert List to String in Python
fruit_list = ['Mango', 'Apple', 'Orange', 'Banana']
# Display list
print(fruit_list)
# Convert list to string
fruit_string = " ".join(fruit_list)
# Display String
print(fruit_string)
# Display type after conversion
print(type(fruit_string))

Output:

['Mango', 'Apple', 'Orange', 'Banana']
Mango Apple Orange Banana
<class 'str'>

Example: Convert List to String in Python

Here, we used a separator(-) that joined with each element of the list in Python. It is helpful when we want a string joined with a specified separator. 

# Example to Convert List to String in Python
fruit_list = ['Mango', 'Apple', 'Orange', 'Banana']
# Display list
print(fruit_list)
# Convert list to string with seperator
fruit_string = "-".join(fruit_list)
# Display String
print(fruit_string)
# Display type after conversion
print(type(fruit_string))

Output:

['Mango', 'Apple', 'Orange', 'Banana']
Mango-Apple-Orange-Banana
<class 'str'

 

Exception: Conversion Error in Python

In previous examples, we used a list of string elements but what if the list contains mixed types of elements. In this case, will the join() method work? No, this method will not work and raise an error. See the below example.

# Example to Convert List to String in Python
mix_list = ['Mango', 'Apple', 'Orange', 'Banana', 25, 20]
# Display list
print(mix_list)
# Convert list to string with seperator
fruit_string = "-".join(mix_list)
# Display String
print(fruit_string)
# Display type after conversion
print(type(fruit_string))

Output:

['Mango', 'Apple', 'Orange', 'Banana', 25, 20]
Traceback (most recent call last):
  File "/tmp/sessions/577b9378153ff72f/main.py", line 6, in <module>
    fruit_string = "-".join(mix_list)
TypeError: sequence item 4: expected str instance, int found

 

Example: Mixed Type List Conversion to String in Python

If a list contains mixed types of elements then use the map() method inside the join() method to first convert non-string type to string and then join them into a single string. See the below example.

# Example to Convert List to String in Python
mix_list = ['Mango', 'Apple', 'Orange', 'Banana', 25, 20]
# Display list
print(mix_list)
# Convert list to string with seperator
fruit_string = "-".join(map(str, mix_list))
# Display String
print(fruit_string)
# Display type after conversion
print(type(fruit_string))

Output:

['Mango', 'Apple', 'Orange', 'Banana', 25, 20]
Mango-Apple-Orange-Banana-25-20
<class 'str'>

 

Related Articles