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 Bootcamp: Go from zero to hero in Python 3
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:
# define strings
firstname = "Bugs"
lastname = "Bunny"
# define our sequence
sequence = (firstname,lastname)
# join into new string
name = " ".join(sequence)
You should see this output:
It can also join a list of words:
words = ["How","are","you","doing","?"]
sentence = ' '.join(words)
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.