Python Tutorial
Python Modify Strings
Python strings are immutable. Methods return a new string — they do not change the original.
upper, lower, strip
Change case and remove whitespace from both ends.
a = " Hello, World! "
print(a.upper())
print(a.lower())
print(a.strip())replace and split
replace() swaps a substring. split() returns a list.
a = "Hello, World!"
print(a.replace("H", "J"))
print(a.split(","))📘 Real-World Deep Dive
<code>str</code> is immutable; every "modify" method actually returns a new string. Knowing which method to call for which job (case, whitespace, suffix, replace) removes entire categories of hand-rolled bugs.
Real-Life Scenario
A small text-normalisation utility that canonicalises whitespace, fixes smart-quotes, and strips file-system-hostile characters from user-supplied titles.
Real-Life Example
import re, unicodedata
def fix_smart_quotes(s: str) -> str:
table = str.maketrans({
"’": "'", "‘": "'",
"“": '"', "”": '"',
"–": "-", "—": "—",
" ": " "})
return s.translate(table)
def normalise_ws(s: str) -> str:
return re.sub(r"\s+", " ", s).strip()
def safe_filename(title: str, maxlen: int = 80) -> str:
folded = unicodedata.normalize("NFKD", title).encode("ascii", "ignore").decode("ascii")
cleaned = re.sub(r"[^A-Za-z0-9._-]+", "-", folded).strip("-") or "untitled"
return cleaned[:maxlen].rstrip("-.")
samples = [
" Hello, "World" — 2026 ",
" [DRAFT] café résumé / ",
"Pay $1,000,000 (US) — invoice.pdf",
]
for raw in samples:
cleaned = normalise_ws(fix_smart_quotes(raw)).title()
print(f"in: {raw!r}")
print(f"out: {cleaned!r} => file: {safe_filename(cleaned)!r}")Expected Output
in: ' Hello, "World" — 2026 '
out: 'Hello, "world" — 2026' => file: 'Hello-world-2026'
in: ' [DRAFT] café résumé / '
out: '[Draft] Café Résumé /' => file: 'Draft-Cafe-Resume'
in: 'Pay $1,000,000 (US) — invoice.pdf'
out: 'Pay $1,000,000 (Us) — Invoice.pdf' => file: 'Pay-1000000-US-invoice.pdf'Common mistakes
- Calling
str.title()on acronyms produces ugly output ("Http" not "HTTP") — usestr.replaceafter. str.strip()by default strips ASCII whitespace only — non-breaking spaces survive.- Calling
str.replacein a loop creates a new string every iteration;str.translateis faster for bulk substitution.
🚀 Performance & Best Practices
- For bulk replacements, define a translation table once:
tbl = str.maketrans({"a":"b", ...}). str.casefold()is the right lower-casing for comparison;str.lower()can miss some Unicode.- For many small edits, accumulate an
io.StringIOwriter and callgetvalue()once at the end.
🧪 Try It Yourself
- Add a step that strips leading/trailing quotes after
normalise_ws. - Implement
squash_punct(s)that converts runs of!!!into a single!. - UTF-8 validity-check the input before normalisation.