runtime
28 / 250
lesson 28 Strings & Text · beginner

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.

You'll be able to
  • 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
The idea

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.

example-1.py · Tidying a typed city
city = "  new YORK "
print("[" + city + "]")
print("[" + city.strip() + "]")
print(city.strip().title())
print(city.upper().strip())
print("[" + city + "]")
example-2.py · A method on the wrong kind of value
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.

example-3.py · Checking an uploaded file name
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 replace replaces *every* match, not only the first one.
Review
  • A method is called with a dot, and string methods always return a new text. Store it to keep it.
  • strip, lower, upper, title and replace build text, while startswith and endswith answer 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.

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Clean and change text with methods — Strings & Text · Runtime