python · level 2 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
cuts a line of text into a list.
Real data often arrives as one long line of text. .split() cuts it into a list of pieces. With empty brackets it cuts wherever there is , so a sentence becomes a list of words.
Put a in the brackets to cut somewhere else. "tea,milk,jam".split(",") cuts at each comma and gives ['tea', 'milk', 'jam']. The separator itself is thrown away.
Each piece is still a string, even if it looks like a number. Convert it with int(), or with float() for decimals like "4.50".
line = "Sam,12,1.5"
name, age, height = line.split(",")
print(name)
print(int(age) + 1)
print(float(height) * 2)
print("the quick brown fox".split()) float() works like int(), but turns text into a decimal number.
guess first
A messy shopping list. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
items = "eggs, flour, sugar".split(",")
print(items)
print(len(items))
your turn
Your turn. Add up a till receipt.
Type three prices with commas between them, like 1.25,0.5,3. Then fill in the separator, and the conversion that turns each piece into a decimal number.
fix it
The scoreboard will not add up. Can you fix it?
- Read the error: TypeError. What type is each piece that
.split()hands back? - Every piece is a string, like
"7", and you cannot add a string to a number. - Change score to int(score) on line 4, then run.
nailed it
you cut text into useful pieces. :D
.split()cuts text into a list at every gap..split(",")cuts at each comma and drops the commas.- Pieces are strings: convert them with
int()orfloat().
new words in your collection
- .split()
- separator
- whitespace
This lesson isn’t saved. A free account remembers every lesson you finish.