Python – Convert List to a String

In this tutorial, we’ll look at how to convert a python list to a string.

You can use the string join() function in a list comprehension to easily create a string from the elements of the list. The following is the syntax:

s = ''.join(str(i) for i in ls)

Here, we iterate through the elements of the list ls converting each to a string object using list comprehension and then join the elements into a string using the string join() method. For more details on the join() method, refer to this guide.

Let’s look at a few examples.

To get a single string from a list of strings, you can use the syntax above. But, since all the items in the list are already string, you don’t need to explicitly convert them into a string. See the example below.

ls = ['a', 'e', 'i', 'o', 'u']
s = ''.join(ls)
print(s)

Output:

aeiou

In the above example, you can see that we directly passed the list to the join() function without converting each item to string. This was possible because the items in the list were already string.

To get a string from a list of integers, you need to explicitly convert each list item to a string (for example, in a list comprehension) before applying the join() function. See the example below.

ls = [1, 2, 3, 4]
s = ''.join(str(i) for i in ls)
print(s)
print(type(s))

Output:

1234
<class 'str'>

In the above example, the string s is created from the items of the list ls containing integer items.

If you’re not sure about the types of items in the list, it’s better to convert them to string and then pass it to the join() function which is used to join string objects.

You can use a custom string to join the items in the list. The above examples used an empty string to join the items but you use any other string like a whitespace ' ', newline character '\n', etc as well. See the example below.

ls = [1, 2, 3, 4]
s = '\n'.join(str(i) for i in ls)
print(s)

Output:

1
2
3
4

Here, we use a newline character '\n' to join the list. The resulting string has each item of the list separated by a newline character.

For more on the python string join() function, refer to the python docs.


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.