In this tutorial, we will explain three ways of converting a list to a string in Python. These are:
- join method
- str/join combination
- map() function
If your list contains only string objects then you may use the join() method to convert the list objects into a string.
Suppose, we have the following list:
This is how you may use the join method:
Learn more about join() function here
First way – an example of list to string Python using join
The join() takes a string separator e.g. space, comma, etc., and joins the elements of the given sequence – a list in that case.
See this example, where we used the above list and converted this to strings by using the join() method. The separator is a comma:
#An example of list to string conversion lst_to_string = ['The','Python','Tutorials'] str_join = ",".join(lst_to_string) print ("After join:",str_join)
The output:
Second way – using str() function
What if a list contains integers, float, or mixed objects?
If your list contains mixed elements like strings, integers, and floats then join() method will produce an error.
The solution to this situation is using the str() function for converting the integers to strings and then using the join method with the separator.
See this example where a list is created with mixed elements. It contains strings, integer,s and float objects.
#An example of list to string conversion lst_mixed = [10, 'The','Python','Tutorials',15.5] str_join = " ".join(str(x) for x in lst_mixed) print ("After str and join:",str_join)
The output
In the output, you can see the integer and float object displayed along with string objects by a space separator.
Third way: using the map function
Another trick for achieving the conversion of the list to string is using the map function with join. The map function takes a function and applies it to iterable which can be a list, tuple, etc.
The map function returns a list of the results after applying that function to the iterable. See the conversion of a list to string by using the map() for a mixed list:
#An example of list to string conversion by map and join lst_mixed = ['List','to','String by map',9.9, 50] str_join_map = " ".join(map(str, lst_mixed)) print ("After map and join:",str_join_map)
Output:
You can see, the list contains three strings, one int, and one float object. The output displays the elements of the list as string after conversion.
Vice Versa – convert string into a list
If you require converting the strings into a list then you may use the split method. The split method takes a delimiter by which the given string is broken and it returns a list of strings. I have covered the split method in detail here with examples.
Example code:
strmet = "String to List" print (strmet.split())
The output will be:
For the complete tutorial, go to the split string tutorial.