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 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'] |
msg = "the long hatch is open"
count = 0
for w in msg.split():
if len(w) > 3:
count = count + 1
print(count) note = "Nova scans the far ring" words = note.split() print(len(words)) print(words[0]) print(words[-2]) print(len(words[3]))
| Statement | True 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. | ? |
Great job! Tomorrow you will do the opposite: join a list back into one string.