Python: How to Convert a List into a String? (The Right Way)

Converting a list of strings into a string is a very common operation.

For example, assume you have a list of words that that look like this:

words = ["Messi", "is", "the", "best", "soccer", "player"]

And you want to convert this into the string:

"Messi is the best soccer player"

How can you do that?

The correct way to achieve this is by using the join method.

>>> words = ["Messi", "is", "the", "best", "soccer", "player"]
>>> sentence = " ".join(words)
>>> sentence
'Messi is the best soccer player'

Now that you know the answer, let me explain the join method in more detail.

The join Method

join() is a method that is defined on the string class.

The general syntax of join is as follows:

str.join(iterable)

where:

  • str is a string representing the separator between the words to be joined.
  • iterable could be any iterable (lists, tuples, string…). This iterable will include all the words to be joined. In this article, I will focus mainly on lists but the same concept applies to tuples, strings, and any iterable for that matter.

Let’s take another example just to make sure everything is clear.

Say you have a list of strings as follows:

fruits = ["apples", "bananas", "strawberries"]

And you would like to convert the list into a single string with all the items in the list separated by a comma.

In this case, the separator is the comma string “, “ and the iterable is the fruits list.

>>> fruits = ["apples", "bananas", "strawberries"]
>>> csv = ", ".join(fruits)
>>> csv
'apples, bananas, strawberries'

Note that this only works if you have a list of strings.

If your list has any item that is not a string, then you will get an error.

>>> words = ["Messi", "is", "number", 1]
>>> sentence = " ".join(words)
TypeError: sequence item 3: expected str instance, int found

So what do you do in a situation like this?

Well, if your list has non-string items that could be converted to strings via the built-in str() function, then you can use the handy map method to map all the items into a string first.

>>> words = ["Messi", "is", "number", 1]
>>> sentence = " ".join(map(str, words))
>>> sentence
'Messi is number 1'

There you go.

So next time you want to convert a list of strings into a single string, don’t create your own custom function to do that. Just use the Join method.

Learning Python?

Check out the Courses section!

Featured Posts

Are you Beginning your Programming Career?

I provide my best content for beginners in the newsletter.

  • Python tips for beginners, intermediate, and advanced levels.
  • CS Career tips and advice.
  • Special discounts on my premium courses when they launch.

And so much more…

Subscribe now. It’s Free.

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments