3. Strings
3.3 String methods
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
String methods are cleaning tools. They scrub, shout or split your text.
- .strip() wipes spaces from both ends.
- .upper() makes everything CAPITAL.
- .split(",") cuts text into a list.
Thumb rule: Methods give you a new string. The old one never changes.
Watch it run · 1
print(" hi ".strip())hi
Watch it run · 2
print("a,b,c".split(","))['a', 'b', 'c']
A method is a built-in action you call with a dot, such as text.lower(). String methods clean and reshape text.
.strip()removes spaces at both ends.lower()and.upper()change the case.replace("a", "b")swaps text.split(",")breaks text into a list.startswith("IN")checks the beginning and givesTrueorFalse
Strings never change in place. Each method returns a new string, so save it: clean = raw.strip(). You can chain methods: raw.strip().lower().
Cleaning a column header
" Order ID ".strip()→"Order ID".lower()→"order id".replace(" ", "_")→"order_id"
Calling raw.strip() on its own line changes nothing. Assign the result: raw = raw.strip().
How it fits together
- " Order ID "
- strip · lower · replace
- "order_id"
Step through the code
Python
raw_header = " Order ID "clean_header = raw_header.strip().lower().replace(" ", "_")print(clean_header)
Output
order_id
Practice in Python ✓ Solved
Normalize raw_header by trimming it, lowercasing it, and replacing spaces with underscores. Print the result.
Expected output
customer_name
Reference solution
raw_header = " Customer Name "
print(raw_header.strip().lower().replace(" ", "_"))
Question 1 · Easy
What does "DATA".lower() give?
Question 2 · Medium
What does "a,b,c".split(",") give?
Question 3 · Hard
raw = " hi ". After raw.strip() on its own line, what is len(raw)?
Key takeaways
String methods return new values you can chain and store.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in