Learning Goals
3 minBy the end of this lesson you can:
- Remove stray spaces from typed input with
strip(). - Compare two pieces of text fairly by putting both in the same case.
- Swap one piece of text for another with
replace().
Warm-Up · The Answer That Was Right
5 minLast lesson you reached into text by position. This quiz compares two whole strings. What does it print?
answer = "Vienna " correct = "Vienna" print(answer == correct) print(len(answer), len(correct))
Answer
Output
False 10 9
One trailing space. The pupil answered correctly and the program marked them wrong — and you cannot see why by looking at it.
input() hands you exactly what was typed, spaces and capitals included. Comparing raw input to a tidy answer fails constantly. The fix is three method calls, and it is today.
New Concept · Methods That Hand Back a New String
12 minThink of a photocopier. You feed in a page, choose a setting, and get a new page out. The original is untouched. Every string method works exactly like that.
messy = " Tokyo " print(messy.strip()) print(messy)
Output
Tokyo Tokyo
messy.strip() does not tidy messy. It returns a tidy copy and leaves the original alone. If you want to keep the result you must store it: messy = messy.strip(). Forgetting this is the second most common bug in this lesson, right after the trailing space itself.
The four you will use every week
city = " Tokyo " print(city.strip()) print(city.strip().upper()) print(city.strip().lower()) print(city.strip().title())
Output
Tokyo TOKYO Tokyo Tokyo
Methods can be chained left to right. city.strip().upper() strips first, then shouts the result.
strip()— removes spaces, tabs and newlines from both ends, never the middle.lower()/upper()— every letter to one case. This is what makes comparing fair.title()— capitalises the first letter of each word. Good for display, not for comparing.replace(old, new)— swaps every occurrence.
order = "hot chocolate, pancake, hot chocolate" print(order.replace("hot chocolate", "coffee")) print(order.replace(",", " |"))
Output
coffee, pancake, coffee hot chocolate | pancake | hot chocolate
Why it matters. Every program that accepts typing needs this. A login that rejects " Mia", a quiz that marks "CAIRO" wrong, a search that misses "Pizza" — all the same missing line.
Worked Example · A Quiz That Is Fair
12 minOne question, marked properly however it is typed.
# capital_quiz.py - marking that survives real typing correct_answer = "Vienna" raw = input("What is the administrative capital of the world? ") # Clean once, store the result, then compare cleaned = raw.strip().lower() print("You typed: ", repr(raw)) print("Compared as:", repr(cleaned)) if cleaned == correct_answer: print("Correct!") else: print("Not quite. The answer is Vienna.")
Output
What is the administrative capital of the world? Vienna You typed: ' Vienna' Compared as: 'Vienna' Correct!
Two details worth stealing:
- Store the cleaned version in its own variable. Keeping
rawmeans you can still show the pupil what they actually typed. repr()shows the quotes, so stray spaces become visible. It is the fastest way to see a whitespace bug.
Notice the stored answer is already lower case. Both sides must be cleaned the same way — cleaning only the input still fails if your answer key has a capital.
Try It Yourself
13 minAsk for a name, then greet the person with their name in title case and no stray spaces. Typing " Leo " should greet Leo.
Hint
raw = input("Your name: ") name = raw.strip().title() print("Welcome,", name + "!")
Start with item = " PIZZA slice ". Produce Pizza slice in one chain of methods, and print it.
The double space in the middle will not go away with strip() — that only touches the ends. Use replace() to deal with it, and say in a comment why the order of your calls matters.
Mini-Challenge 🔥 · Debug: The Password That Never Matches
8 minZoe's login rejects the correct password every time. There are two mistakes.
# login.py - buggy
stored = "Sukan2026"
typed = input("Password: ")
typed.strip()
if typed.lower() == stored:
print("Welcome back!")
else:
print("Wrong password.")Answer
typed.strip()throws its result away. The tidy copy is made and immediately discarded, because nothing stores it. It must betyped = typed.strip().- Only one side is lowered.
typed.lower()gives"sukan2026", butstoredstill has its capital S, so they can never be equal. Either lower both, or — better for a password — lower neither.
A password is the one case where you should not ignore case, so the fix keeps it exact:
# login.py - fixed stored = "Sukan2026" typed = input("Password: ") typed = typed.strip() if typed == stored: print("Welcome back!") else: print("Wrong password.")
Output
Password: Sukan2026 Welcome back!
Strip the accidental space, keep the deliberate capital. Knowing which to ignore is the real skill.
Recap
3 minString methods return a new string and never change the original, so the result must be stored. strip() clears both ends, lower() and upper() make comparing fair, title() is for display, and replace() swaps every occurrence. Clean both sides of a comparison the same way.
Vocabulary Card
- method
- A function that belongs to a value, called with a dot:
text.strip(). - immutable
- Cannot be changed in place. Strings are immutable, so methods return copies.
- chaining
- Calling a method on the result of another:
text.strip().lower(). - whitespace
- Spaces, tabs and newlines — invisible characters that break comparisons.
Homework
4 minWrite tidy_names.py. Five classmates have typed their names badly — you write them into the file yourself, each with a different problem: leading spaces, ALL CAPS, all lower case, a trailing space, a double space in the middle.
- Print each name exactly as typed, using
repr()so the problem is visible. - Print each name cleaned to title case with single spaces.
- End with a line saying how many names you fixed.
Bring the file and its output next class.
Sample · tidy_names.py
# tidy_names.py - five badly typed names, cleaned the same way messy_names = [ " mia Cole", "LEO TAN ", "ana Rivera", " Hugo Kumar ", "ella izzati ", ] print("Before:") for name in messy_names: print(" ", repr(name)) print() print("After:") for name in messy_names: tidy = name.strip().replace(" ", " ").title() print(" ", tidy) print() print("Fixed", len(messy_names), "names.")
Output
Before: ' mia Cole' 'LEO TAN ' 'ana Rivera' ' Hugo Kumar ' 'ella izzati ' After: Mia Tom Leo Reed Ana A/P Rivera Hugo Kumar Ella Izzati Fixed 5 names.
Note "Hugo Kumar" had three spaces — one replace(" ", " ") leaves two. A second pass fixes it, and lesson 3 shows the proper tool. Spotting that limit is worth more than hiding it.