Python Strings & f-strings: Cleaning Text Without Tears
Clean messy user input with .strip() and .lower(), split and join text, and format values cleanly with Python f-strings.
You'll learn how to embed variables directly into text with f"...", why string methods return new strings instead of changing the original, and how .strip(), .split(), and .join() handle messy text. Assumes basic Python variables.
1. Humans type terrible input
Users type " Gerald@Example.COM \n" with leading spaces, random caps, and trailing newlines. If you check if email == "gerald@example.com", it fails.
Python strings come with built-in cleaning tools. One crucial catch: strings are immutable—you cannot alter a string in place, so every method hands back a new cleaned string:
raw = " Gerald@Example.COM "
clean = raw.strip().lower()
print(repr(raw))
print(repr(clean))' Gerald@Example.COM '
'gerald@example.com'raw didn't change at all; clean got the trimmed, lowercase version.
2. f-strings: dropping variables straight into text
Gluing text and numbers with + crashes ("age: " + 20 raises TypeError). Put an f right before the opening quote and drop any variable or expression inside {}:
name = "Gerald"
coffees = 3
bill = 14.5
print(f"{name} drank {coffees} coffees (${bill:.2f} total).")Gerald drank 3 coffees ($14.50 total)..2f means "format as a decimal with 2 digits after the dot." And for quick debugging, print(f"{coffees=}") prints coffees=3 automatically.
Try print(f"{10 / 3:.3f}") in Python to verify it prints 3.333.
3. Splitting and joining
.split(",")chops one string into a list of pieces.", ".join(items)glues a list of strings back into one string.
tags = "python,go,web".split(",")
print(tags)
print(" | ".join(tags))['python', 'go', 'web']
python | go | webCommon mistakes
| Error / Bug | What it means | Fix |
|---|---|---|
TypeError: can only concatenate str (not "int") to str | Used "x: " + 5 | Use f"x: {5}" instead |
s.strip() seemed to do nothing | Forgot to assign s = s.strip() | Strings are immutable; save the return value |
",".join([1, 2]) raises TypeError | .join() only accepts strings | Convert items first: ",".join(str(x) for x in [1, 2]) |
Practice
- What does
" HI ".strip().lower().title()return?
Answer: "Hi".
What you learned
- Strings are immutable—save the result of
.strip(),.lower(), or.replace(). f"{val:.2f}"formats numbers and expressions cleanly inside strings..split()turns a string into a list;.join()turns a list of strings back into one string.
Video walkthrough
YouTubeClick play to load video (YouTube)