python · level 2 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
.join() glues a list of strings into one line.
.join() is the opposite of .split(). You call it on the separator and hand it the list. ", ".join(guests) puts a comma and a space between every guest, making one line.
The separator only goes between items, never at the start or end, so there is no stray comma to tidy up. Any string can be the separator, such as " and " or " > ".
Every item must already be a string. A list of numbers gives a TypeError, so convert them first.
guests = ["Ana", "Ben", "Cy"]
print(", ".join(guests))
print(" and ".join(guests))
steps = ["Home", "Shop", "Socks"]
print(" > ".join(steps)) Read ", ".join(guests) as: glue the guests together with a comma and a space.
guess first
Numbers in a row. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
ages = [9, 12, 15]
print(" / ".join(ages))
your turn
Your turn. Write a tidy shopping message.
Add four items to the list. Then choose a separator that puts a comma and a space between them.
fix it
The lottery numbers will not join. Can you fix it?
- Read the error: TypeError. What type are the items in
words? .join()needs strings, but the loop copies each number as it is.- On line 4, append str(number) instead of number, then run.
nailed it
you glued lists back into text. :D
separator.join(list)turns a list into one string.- The separator goes between items, never at the ends.
- Convert numbers with
str()before you join them.
new words in your collection
- comma-separated
This lesson isn’t saved. A free account remembers every lesson you finish.