Learning Goals
3 minBy the end of this lesson you can:
- Break a sentence into a list of words with
split(). - Split on a chosen separator, such as a comma, to read one line of data.
- Rebuild a string from a list with
join(), choosing the glue.
Warm-Up · The Name That Would Not Generalise
5 minLesson 1 found a surname initial by hard-coding index 6. Try that code on a different name.
full_name = "Leo Reed" print(full_name[0]) print(full_name[6])
Answer
Output
W e
Index 6 landed in the middle of "Jie". The position of the space is different in every name, so no fixed number can work.
The string already knows where its spaces are. Ask it to break itself apart and the positions stop mattering.
New Concept · One String In, Many Strings Out
12 minThink of a hot dog stick with pieces of chicken on it. split() slides the pieces off into a bowl; join() threads them back onto a stick of your choosing.
full_name = "Leo Reed" parts = full_name.split() print(parts) print(len(parts)) print(parts[0]) print(parts[-1])
Output
['Wei', 'Jie', 'Reed'] 3 Wei Reed
Now the surname is parts[-1] for every name, however many middle names it has. That is the whole point.
split() with no arguments is the clever oneCalled with nothing, it splits on any run of whitespace and throws away the empties. So "Hugo Kumar".split() gives two words, not four — the triple-space problem from lesson 2 solved properly.
Splitting on something else
Give split() a separator and it uses that instead.
line = "Mia,78,2 Ceria" fields = line.split(",") print(fields) print("Name: ", fields[0]) print("Score:", fields[1])
Output
['Mia', '78', '2 Ceria'] Name: Mia Score: 78
That is a CSV line — the shape most exported data arrives in. Note fields[1] is the string "78", not the number 78. Use int() before doing sums with it.
join() — the other direction
The odd part is that join is called on the glue, not on the list.
words = ["rice", "lemak", "chicken"] print(" ".join(words)) print("-".join(words)) print(", ".join(words)) print("".join(words))
Output
chicken pizza pizza-chicken rice, lemak, chicken pizzachicken
Read "-".join(words) as "put a dash between each of these". Every item must already be a string — a list with a number in it raises TypeError.
Why it matters. Split to take data apart, work on the pieces as a list, join to put it back for display. That round trip is behind search boxes, CSV readers, tag editors and half the text handling you will ever write.
Worked Example · Initials for Any Name
12 minThe lesson 1 mini-challenge, done properly — this time it works for every name.
# initials.py - split, take the first letter of each word, join back names = ["Ella Izzati", "Leo Reed", "Ana", "Muhammad Felix Hassan"] for full_name in names: parts = full_name.split() letters = [] for part in parts: letters.append(part[0].upper()) initials = ".".join(letters) print(full_name, "->", initials + ".")
Output
Ella Izzati -> N.I. Leo Reed -> W.J.T. Ana -> P. Muhammad Felix Hassan -> M.A.B.H.
Three ideas working together, and each is one line:
split()turns one name into however many words it has.part[0]— lesson 1 — takes the first character of each.".".join(letters)glues them with the separator you want.
The single-word name needed no special case, and neither did the four-word one. Splitting removed the counting, and with it the bug.
"bin" became B., which no one would write by hand. Fixing it means deciding which words to skip — a rule about names, not about Python. Real text work is full of these; the code is rarely the hard part.
Try It Yourself
13 minAsk for a sentence. Print how many words it has, then print the first and the last word.
Hint
sentence = input("Type a sentence: ") words = sentence.split() print("Words:", len(words)) print("First:", words[0])
An order arrives as "pizza,2,3.50": item, quantity, unit price.
- Split it into three fields.
- Convert the quantity and price to numbers.
- Print a line such as
2 x Pizza = $7.00.
Use title() from lesson 2 for the item name. Keep it — lesson 6 builds a whole receipt out of exactly this.
Mini-Challenge 🔥 · Debug: The Tag List That Fell Apart
8 minNia is tidying blog tags. Her script crashes, and the line it crashes on is not the line that is wrong. There are two mistakes.
# tags.py - buggy
raw = "python, coding , robotics, ai "
tags = raw.split()
tidy = []
for tag in tags:
tidy.append(tag.strip().title())
print(tags.join(", "))Answer
raw.split()splits on spaces, not commas. The tags are comma separated, so this gives['python,', 'coding', ',', 'robotics,', 'ai']— commas stuck to words, and one entry that is just a comma. It must beraw.split(",").tags.join(", ")is backwards, and it joins the wrong list.joinis called on the glue:", ".join(tidy). Calling it on a list raisesAttributeError: 'list' object has no attribute 'join'.
The working version:
# tags.py - fixed raw = "python, coding , robotics, ai " tags = raw.split(",") tidy = [] for tag in tags: tidy.append(tag.strip().title()) print(", ".join(tidy))
Output
Python, Coding, Robotics, Ai
Splitting on the comma keeps the spaces, which is why each tag still needs strip(). Split on the real separator, then clean each piece — that order is the pattern.
Recap
3 minsplit() turns a string into a list — with no argument it splits on any whitespace, with one it splits on that separator. join() goes the other way and is called on the glue, not the list. Split, work on the list, join back: that round trip handles most real text.
Vocabulary Card
- split
- Breaks a string into a list of pieces at each separator.
- join
- Builds one string from a list, placing the glue between items.
- separator
- The character split cuts at — a space by default, often a comma.
- CSV
- Comma-separated values: one record per line, fields split by commas.
Homework
4 minWrite class_list.py. Start with one long string holding five classmates separated by semicolons, some with stray spaces.
- Split it into a list of names.
- Clean each name to title case.
- Print them numbered, one per line.
- Print them again as a single line separated by
" · ". - Print the initials of each name, using the worked example as your guide.
Bring the file next class.
Sample · class_list.py
# class_list.py - one messy string in, three tidy views out raw = "mia Cole; Leo tan ; ana Rivera;hugo kumar ; ella izzati" names = [] for piece in raw.split(";"): names.append(piece.strip().title()) print("Class list") for i in range(len(names)): print(i + 1, "-", names[i]) print() print("One line:", " . ".join(names)) print() print("Initials:") for name in names: letters = [] for part in name.split(): letters.append(part[0]) print(" ", name, "->", ".".join(letters) + ".")
Output
Class list 1 - Mia Tom 2 - Leo Reed 3 - Ana Rivera 4 - Hugo Kumar 5 - Ella Izzati One line: Mia Tom . Leo Reed . Ana Rivera . Hugo Kumar . Ella Izzati Initials: Mia Tom -> A.R. Leo Reed -> W.J.T. Ana Rivera -> P.M. Hugo Kumar -> A.K. Ella Izzati -> N.I.
Splitting on ";" keeps the spaces, so each piece still needs strip(). If your names came out with odd capitals, check that title() runs after strip(), not before.