String Methods in Practice
About 15 minutes
Why this matters
Most real data is text: names typed by people, lines from files, web pages. It arrives messy, with extra spaces, odd capitals and punctuation. A handful of string methods clean most of it up.
The idea
Strings cannot be changed, so every method returns a new string (or a list):
raw = " hello, Python World "
raw.strip() # 'hello, Python World' (trims both ends)
raw.lower(), raw.upper()
raw.title() # ' Hello, Python World '
raw.replace("l", "L") # swaps every 'l'
raw.split() # ['hello,', 'Python', 'World'] (on whitespace)
"a,b,c".split(",") # ['a', 'b', 'c'] (on a separator)
"-".join(["a", "b"]) # 'a-b'
Asking questions about text:
"python".startswith("py") # True
"report.csv".endswith(".csv") # True
"banana".count("a") # 3
"banana".find("n") # 2 (-1 if missing)
"abc".isalpha(), "123".isdigit(), "a1".isalnum()
Remember the pattern from lists: split into pieces, work on each piece, join them back.
Try it
Take " the QUICK brown fox " and produce "The Quick Brown Fox" using split, capitalize and join.
Your turn
Write three functions that return their answers:
clean_name(raw): tidy a typed name. Remove extra spaces and fix capitals:clean_name(" aDA LOVElace ")is"Ada Lovelace".initials(name):initials("ada lovelace")is"A.L.".is_palindrome(text):Trueif the text reads the same backwards, ignoring capitals, spaces and punctuation."A man, a plan, a canal: Panama"is a palindrome.
Recap
- String methods return new strings; the original never changes.
splitandjoinconvert between text and lists;striptrims the ends.- Test with
startswith,endswith,in,isalphaandisdigit.
Common mistakes
- Expecting
text.strip()to changetext. Assign the result:text = text.strip(). split(" ")vssplit(): with an explicit space, repeated spaces produce empty strings.- Using
findas a condition:-1is truthy, and0(found at the start) is falsy.