← Back to Python, page 2

python-0036 · Easy fresher

What are the most useful string methods for cleaning user input?

strip removes surrounding whitespace, lower or casefold normalise case, replace and split reshape text, startswith and endswith test prefixes, and isdigit or isalpha check content. Strings are immutable, so every method returns a new string that must be assigned.

Full answer
python
raw = "  ASHA.Rao@Example.COM  "
email = raw.strip().lower()
print(repr(email), email.endswith("@example.com"))
name = "  asha   rao "
print(" ".join(name.split()).title())
phone = "98-765 43210"
digits = phone.replace("-", "").replace(" ", "")
print(digits, digits.isdigit(), len(digits) == 10)
print("Straße".lower(), "Straße".casefold())
s = "pen"
s.upper()
print(s)

Output:

text
'asha.rao@example.com' True
Asha Rao
9876543210 True True
straße strasse
pen

strip().lower() gives a clean, comparable email. ' '.join(name.split()) collapses runs of spaces, and title() capitalises each word. Removing separators before isdigit() checks a phone number. casefold() is stronger than lower() for case-insensitive comparison of international text, turning 'ß' into 'ss'. The last lines show immutability: s.upper() returned a new string that was thrown away, so s is still 'pen'.

python
raw = "  ASHA.Rao@Example.COM  "
email = raw.strip().lower()
print(repr(email), email.endswith("@example.com"))
name = "  asha   rao "
print(" ".join(name.split()).title())
phone = "98-765 43210"
digits = phone.replace("-", "").replace(" ", "")
print(digits, digits.isdigit(), len(digits) == 10)
print("Straße".lower(), "Straße".casefold())
s = "pen"
s.upper()
print(s)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • strip, lower, split and join cover most cleaning
  • casefold for international comparisons
  • isdigit checks content
  • Strings are immutable
  • Assign method results

Common mistakes

  • Calling a string method without using the result
  • Using lower() for Unicode-insensitive matching

Follow-ups

  • How would you validate an email properly?
  • When would you use regular expressions instead?

Tips

  • Show immutability