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 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 |
fuel = "30,45,20"
parts = fuel.split(",")
print(parts) | Statement | True 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. | ? |
line = "rope,clamp,glue,tape,lamp"
parts = line.split(",")
print(len(parts))
print(parts[0])
print(parts[-1]) | Statement | True 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. | ? |
Clean cutting! Tomorrow you will split a sentence into words.