Module 03 · Lesson 04
String Methods & Text Sanitization
Clean and reshape text with string methods: change case, strip spaces, split into words and join them back, find and replace, and test what a string contains.
- About 8 minutes
- Beginner friendly
- 12-question quiz at the end
What you will learn
- Change the case
- Strip, split and join
- Find and replace
- Chain methods
Tools built into every string
Every string comes with methods: commands you call with a dot, like `name.upper()`. Each gives back a new string.
Case
upper(),lower()andtitle()change capital letters.Tidy
strip()removes spaces from both ends, so" Sam "becomes"Sam".Split and join
split()breaks text into a list of words.", ".join(words)glues them back together.Find and replace
find(),count()andreplace()search inside the text.Test
isdigit(),isalpha()andstartswith()answer True or False questions about the text.
Tidy text everywhere
People type messy text. Programs tidy it up before using it.
- Sign-inEmails are stripped and made lower case, so
Ana@Mail.comstill matches. - HashtagsA title is split into words and joined with no spaces to make a tag.
- File namesSpaces are replaced with underscores so the name is safe to save.
- Chat filtersMessages are lowered and searched for words that should be hidden.
Two methods in a row
Each method hands back new text, so the next method can work on it. Tap each part to see its job.
Part 1 of 3
messy text:A space at each end and two capital letters.
Prints hi there
Clean and change text
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Case
Each method gives back a new string. The original stays the same.
Your turn: Use swapcase() and see what it does.
msg = "hello World" print(msg.upper()) print(msg.lower()) print(msg.title()) print(msg)
Press Run to see what it prints.Watch messy text get tidy
Press Step to run one line at a time. Each line makes a new, tidier value.
Ready. Press Step to run the first line.
- raw = " tea, COFFEE, juice "
- clean = raw.strip().lower()
- drinks = clean.split(", ")
- menu = " | ".join(drinks)
- print(menu)
- print(drinks[1].title())
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.How many?
print("banana".count("a"))0 of 6 answered
Common method misconceptions
Each card is something beginners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
s.lower() s.upper() s.title() s.capitalize()
s.strip() s.lstrip() s.rstrip() s.strip("-")
s.split() s.split(",") ", ".join(items)
s.replace("a", "b") s.count("x") s.find("x") s.index("x")
s.startswith("ab") s.endswith((".jpg", ".png"))
s.isdigit() s.isalpha() s.isalnum()
s.strip().lower() # chainingPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Tidy a list of names
A sign-up sheet has names typed with stray spaces and random capitals, separated by commas. Turn it into a clean, title-cased list, sorted, and print it as one line.
sheet = " ada lovelace, ALAN turing ,grace HOPPER "
names = []
for part in sheet.split(","):
names.append(part.strip().title())
print(names)
print(" | ".join(sorted(names)))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Calling a method and not keeping the result
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
email = " Ana@Mail.com " email.strip().lower() print(email)
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Publishing
Making a web address slug
A blog turns each article title into the readable part of its web address, called a slug, so How to Bake Bread becomes how-to-bake-bread.
Why Python fits
Lowercasing and keeping only letters, digits and spaces removes the punctuation.
split()with no argument collapses every run of spaces, and joining with dashes gives a slug that is safe in a web address.Pythontitle = " How to Bake Bread: A Beginner's Guide " cleaned = "" for ch in title.lower(): if ch.isalnum() or ch == " ": cleaned += ch slug = "-".join(cleaned.split()) print(slug)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
What is the difference between split() and split(" ")?
How do I remove all spaces, not just at the ends?
Is isdigit() enough to check for a number?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.