W3docs

How to concatenate (join) items in a list to a single string

You can use the join() method to concatenate (join) items in a list to a single string in Python.

You can use the join() method to concatenate (join) items in a list to a single string in Python. The join() method takes one argument, which is the list of strings to be joined.

Here's an example:

Join a list of strings in Python

words = ['this', 'is', 'a', 'sentence']
sentence = ' '.join(words)
print(sentence)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use join() to join a list of other types by converting them first to string.

Join a list of numbers to create a string in Python

numbers = [1, 2, 3, 4]
numbers_str = ' '.join(str(n) for n in numbers)
print(numbers_str)

In this example, the join() method takes a generator expression that converts each number in the list to a string, and then joins them with a space.