Clean and change text with methods
strip, lower, upper, title and replace each build a new text. startswith and endswith answer True or False. The original text never changes.
- Call a method with a dot, chain two methods, and store the new text it returns
- Explain why
name.strip()on its own line changes nothing - Clean both sides before comparing text that people typed
Text typed by people is messy. It has extra spaces, random capitals and different separators. A method is a function that belongs to a value, and you call it with a dot: city.strip().
String methods never change the text they are called on, because a Python string can't be changed at all. Each method gives back a new text, and you keep it by storing it: city = city.strip().
Run each example to see what it prints. Running examples doesn't count toward progress.
city = " new YORK " print("[" + city + "]") print("[" + city.strip() + "]") print(city.strip().title()) print(city.upper().strip()) print("[" + city + "]")
zip_code = 48301 print(zip_code.startswith("4"))
Some methods answer a question instead of building text. startswith and endswith give back True or False. replace(old, new) swaps every match. Together they handle checks such as *is this a CSV file?* or *is this SKU in the home category?*, as long as you clean the text first.
filename = " Sales_Q3.CSV " clean = filename.strip().lower() print(clean) print(clean.endswith(".csv")) print(filename.endswith(".csv")) print(clean.replace("_", " ").replace(".csv", ""))
When to use it: before comparing or storing anything a person typed. Mistakes to avoid:
- Calling a method without storing the result.
name.strip()on its own line does nothing useful. - Cleaning only one side of a comparison.
- Forgetting that
replacereplaces *every* match, not only the first one.
- A method is called with a dot, and string methods always return a new text. Store it to keep it.
strip,lower,upper,titleandreplacebuild text, whilestartswithandendswithanswer True or False.- Clean both sides before comparing text that people typed.
- Next: put values into a sentence, with control over decimals and widths, using f-strings.