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

Tuesday

Split into words
// Decode the comms log
⏱ about 15 min

Tuesday: Split into words

A message from the shuttle pilot crackles in: "dock at gate four now". Rocket wants to know how many words it has, and what the last word is.

"There are no commas this time," he says. "So what do I split on?"

Raven reads the message slowly. "What do you notice between the words?" Rocket snaps his fingers. "Spaces!" Nova gives a bright flash. "Would you like a hint? Leave the brackets empty, and Python will split on spaces for you."

split with empty brackets

split() with nothing in the brackets cuts at spaces.

Extra spaces do not make empty items. Python skips them.

msg = "dock at gate four now"
words = msg.split()
print(words)
print(len(words))
print(words[-1])
The screen shows
['dock', 'at', 'gate', 'four', 'now']
5
now
alert = "fuel   low   on   deck"
print(alert.split())
The screen shows
['fuel', 'low', 'on', 'deck']
How many words in "all crew to the hatch".split()?
What is "all crew to the hatch".split()[1]?

Loop over the words

msg = "the long hatch is open"
count = 0
for w in msg.split():
    if len(w) > 3:
        count = count + 1
print(count)
What number does the program above show?
WHY THIS EXERCISEA loop over split words lets a program study every word in a message.
Try it
Pick a sentence from a book.
Count its words the way split would.

Practice lab: words in a note

note = "Nova scans the far ring"
words = note.split()
print(len(words))
print(words[0])
print(words[-2])
print(len(words[3]))
What does line 3 show?
What does line 4 show?
What does line 5 show?
What does line 6 show?
SPACES CHECK
  • Read the question.
  • Tap your answer.
What does "go now".split() give? It has two spaces in the middle.
split() with empty brackets cuts at what?
How many words are in "a b c d".split()?
StatementTrue or false?
"hi there".split() has 2 items.?
Extra spaces make empty items with split().?
words[-1] is the last word.?
split() keeps the spaces in the list.?
WHY THIS EXERCISEsplit() throws away all the spaces and keeps only the words.
A loop counts the words longer than 4 letters in "every pod has fresh water". What is the count?
WHY THIS EXERCISEevery, fresh and water have 5 letters each. pod and has are too short.

Great job! Tomorrow you will do the opposite: join a list back into one string.

← Monday