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

Monday

Split at the commas
// Decode the comms log
⏱ about 15 min

Monday: Split at the commas

The supply ship sends its cargo list over the radio. It arrives as one long string: water, comma, oats, comma, tape, comma, lamps. All squished together.

"I can't use an index on this," Rocket says. "Index 0 is just the letter w!"

Raven studies the string. "What do you notice about the commas? They sit between every item." Nova traces a dotted line at each comma. "Would you like a hint? Python can cut a string wherever a certain character appears."

split makes a list

split cuts a string at every separator and gives back a list.

Put the separator inside the brackets, in quote marks. The separator itself is thrown away.

line = "water,oats,tape,lamps"
items = line.split(",")
print(items)
print(len(items))
print(items[2])
The screen shows
['water', 'oats', 'tape', 'lamps']
4
tape
  • Before split: one string with 21 characters.
  • After split: a list with 4 items.
  • Now each item has its own index, just like any list.
How many items are in "a,b,c,d,e".split(",")?
WHY THIS EXERCISEThere is always one more piece than separators. That rule helps you check a split.
fuel = "30,45,20"
parts = fuel.split(",")
print(parts)
WHAT DID SPLIT MAKE?
  • Read the question.
  • Tap your answer.
What does the program above show?
StatementTrue or false?
split gives back a list.?
The commas are kept in the list.?
"red;blue".split(";") has 2 items.?
"red;blue".split(",") has 2 items.?
WHY THIS EXERCISEIf the separator is not in the string, nothing gets cut. You get a list with one item.
Try it
Write a list of four snacks with commas between them, like a radio message.
Draw lines where split would cut.

Practice lab: split the supply line

line = "rope,clamp,glue,tape,lamp"
parts = line.split(",")
print(len(parts))
print(parts[0])
print(parts[-1])
What does line 3 show?
What does line 4 show?
What does line 5 show?
How many commas are in line?
SPLIT CHECK
  • Read the question.
  • Tap your answer.
What does "x;y;z".split(";") give?
What does "7,8".split(",") make?
How many items does "one".split(",") give?
StatementTrue or false?
A split list has one more item than separators.?
split changes the original string.?
"a-b-c".split("-") has 3 items.?
split can only cut at commas.?
WHY THIS EXERCISEsplit leaves the original string alone and makes a brand new list.
Which string is at index 2 of "10,20,30,40".split(",")?
WHY THIS EXERCISEThe pieces are "10", "20", "30" and "40". Index 2 is the third piece.

Clean cutting! Tomorrow you will split a sentence into words.