Hit enter after type your search item

Convert a List to String in Python by join method

If your list contains only string objects then you may use the join() function for converting the list objects into the string.

Suppose, we have the following list:

lst_to_string = [‘The’,’Python’,’Tutorials’]

This is how you may use the join method:

str_join = ” “.join(lst_to_string)

Note that, The Python join method concatenates the string of a given sequence. The join() function is not specific to the list only. You may apply it to other sequences e.g tuple, range etc. Learn more about join() function here

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:

See online demo and code


The output:

Python list to string

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 and float objects.

See online demo and code


The outputlist to-string conversion

In the output, you can see the integer and float object displayed along with string objects by a space separator.

Another 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 that can be a list, tuple etc.

The map function returns a list of the result after applying that function to the iterable. See the conversion of a list to string by using the map() for a mixed list:

list-to-string map

See online demo and code


 

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 string. I have covered the split method in detail here with examples.

Example code:

strmet = “String to List”

print (strmet.split())

The output will be:

[‘String’, ‘to’, ‘List’]

For the complete tutorial, go to the split string tutorial.

This div height required for enabling the sticky sidebar