← Back to course
Code Crew G4 / Week 06 / Wednesday
3/6
Week 06 Β· Split and join

Wednesday

Join the pieces
// Decode the comms log
⏱ about 15 min

Wednesday: Join the pieces

Rocket has the crew list ready for the flight board: Rocket, Raven and Kai. He prints the list, and the board shows square brackets and quote marks.

"That looks like code, not a sign," he sighs. Raven tilts her head. "What do you notice? We want commas and spaces between the names, and nothing else."

Nova hums a little tune. "Would you like a hint? Split cuts a string into a list. Something else glues a list back into a string."

join glues a list together

join makes one string from a list of strings.

First write the separator string. Then a dot, join, and the list in brackets.

crew = ["Rocket", "Raven", "Kai"]
print(crew)
print(", ".join(crew))
print("-".join(crew))
print("".join(["N", "O", "V", "A"]))
The screen shows
['Rocket', 'Raven', 'Kai']
Rocket, Raven, Kai
Rocket-Raven-Kai
NOVA
  • The separator goes between the pieces, not before the first or after the last.
  • An empty separator "" glues the pieces with nothing between them.
  • Every item in the list must be a string.
parts = ["deck", "3", "clear"]
print(" ".join(parts))
print("/".join(parts))
First line on the screen
Second line on the screen
PICK THE SEPARATOR
  • Read the question.
  • Tap your answer.
Which line shows a+b+c from the list ["a", "b", "c"]?
PUT THE LINES IN ORDER SO THE SCREEN SHOWS READY, SET, GO
  • ?calls.append("go")
  • ?calls.append("set")
  • ?print(", ".join(calls))
  • ?calls.append("ready")
  • ?calls = []
WHY THIS EXERCISEBuild a list, then join it. You will use this pattern on Friday.
Try it
Write three words on scraps of paper.
Join them on the table with a different separator each time: a space, a dash, nothing.

Practice lab: one list, four strings

days = ["Mon", "Tue", "Wed"]
print(" ".join(days))
print(", ".join(days))
print("".join(days))
print(" and ".join(days))
What does line 2 show?
What does line 4 show?
What does line 5 show?
JOIN CHECK
  • Read the question.
  • Tap your answer.
Where does the separator go?
What does "-".join(["4", "2"]) give?
Which list can join work on?
StatementTrue or false?
"".join(["a", "b"]) gives "ab"?
join puts a separator after the last piece.?
split and join are opposites.?
The separator comes after the dot.?
WHY THIS EXERCISEThe separator comes first. split cuts apart, and join glues together.
How many dashes are in "-".join(["a", "b", "c", "d"])?
WHY THIS EXERCISEThe result is a-b-c-d. There is one dash in each gap.

Smooth joining! Tomorrow you will use split and join to decode the comms log.

← Tuesday