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. The join()
method takes one argument, which is the list of strings to be joined.
Here's an example:
words = ['this', 'is', 'a', 'sentence']
sentence = ' '.join(words)
print(sentence)
Watch a video course
Python - The Practical Guide
You can also use join()
to join a list of other types by converting them first to string.
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.