The join(sequence) method joins elements and returns the combined string. The join methods combines every element of the sequence.
Combine list of words?
Combine them into a sentence with the join(sequence) method. The method is called on a seperator string, which can be anything from a space to a dash.
This is easier than using the plus operator for every word, which would quickly become tedious with a long list of words.
Related course: Complete Python Programming Course & Exercises
Example
The join method takes a sequence as argument. The sequence is written as single argument: you need to add brackets around the sequence.
If you’d like, you can pass a variable holding the sequence as argument. This makes it easier to read. We’ll use a space a seperator string in the example below.
Try the program below:1
2
3
4
5
6
7
8
9
10# define strings
firstname = "Bugs"
lastname = "Bunny"
# define our sequence
sequence = (firstname,lastname)
# join into new string
name = " ".join(sequence)
print(name)
You should see this output:
It can also join a list of words:1
2
3words = ["How","are","you","doing","?"]
sentence = ' '.join(words)
print(sentence)
If you are a beginner, then I highly recommend this book.
Exercise
Try the exercises below
- Create a list of words and join them, like the example above.
- Try changing the seperator string from a space to an underscore.