Working with strings in depth
Master the essential string methods, formatting styles, multi-line strings, and why immutability matters.
- Use the most important str methods for cleaning, splitting, and searching
- Format strings with f-strings and .format()
- Write multi-line strings with triple quotes
- Explain string immutability and what it means for your code
The introductory strings lesson covered indexing, slicing, and the basics of f-strings. Now you'll meet the full method toolbox — the one you'll reach for constantly when processing text from files, APIs, or user input.
Cleaning and normalising
Real-world strings rarely arrive in a tidy form. These three methods handle the most common clean-up tasks:
" hello world ".strip() # "hello world" — removes surrounding whitespace
" hello world ".lstrip() # "hello world " — left side only
" hello world ".rstrip() # " hello world" — right side only
"Hello World".lower() # "hello world"
"Hello World".upper() # "HELLO WORLD"strip() is almost always the first thing you do with a line read from a file —
the trailing newline and any leading spaces vanish in one call.
Splitting and joining
split() converts a string into a list; join() is the inverse:
"one,two,three".split(",") # ["one", "two", "three"]
"hello world".split() # ["hello", "world"] — splits on any whitespace
",".join(["one", "two", "three"]) # "one,two,three"
" | ".join(["a", "b", "c"]) # "a | b | c"The join pattern is particularly clean: call it on the separator string and
pass the list as the argument. Building strings with + in a loop is both
slower and harder to read.
Searching and replacing
"hello world".replace("world", "Python") # "hello Python"
"hello world".find("world") # 6 — index of first match
"hello world".find("xyz") # -1 — not found
"hello world".count("l") # 3
"hello world".startswith("hello") # True
"hello world".endswith("world") # Truefind() returns -1 when the substring isn't present. If you only need to
know whether it's there at all, "needle" in haystack is cleaner:
"world" in "hello world" # True
"xyz" in "hello world" # FalseString formatting: f-strings and .format()
You already know f-strings from the previous lesson. They're the preferred style in modern Python (3.6+):
name, score = "Ada", 98
f"{name} scored {score}/100" # "Ada scored 98/100"
f"{score:.1f}%" # "98.0%" — format spec after the colon
f"{name!r}" # "'Ada'" — repr() of the value.format() is the older style you'll see in existing codebases:
"{} scored {}".format(name, score) # positional
"{name} scored {score}".format(name=name, score=score) # keywordBoth work; f-strings are shorter and catch name errors at definition time.
Format specs inside f-strings ({value:.2f}, {value:>10}, {value:,})
give you fine-grained control over decimal places, alignment, and number
separators — without importing anything.
Multi-line strings
Triple quotes (""" or ''') create strings that can span multiple lines:
message = """
Dear Ada,
Your submission has been received.
Thank you.
"""The leading newline after """ is often unwanted; you can strip it with
.strip() or start the string content on the same line as the opening quotes.
Multi-line strings are handy for SQL queries, HTML templates, and docstrings.
String immutability
Strings are immutable — no method ever changes the original. Every method returns a new string:
name = "ada"
name.upper() # returns "ADA" but name is still "ada"
print(name) # "ada"
# Correct: reassign if you want to keep the result
name = name.upper()
print(name) # "ADA"This is why chaining methods works:
" Ada Lovelace ".strip().lower().replace(" ", "_")
# "ada_lovelace"Each method call receives the return value of the previous one.
Write normalize_name(name) that strips surrounding whitespace, then capitalizes the first letter of each word. " ada lovelace " -> "Ada Lovelace".
normalize_name("ada lovelace") → "Ada Lovelace"normalize_name(" grace hopper ") → "Grace Hopper"Where to go next
You're now fluent with the string toolbox. The lab: filter and report puts boolean logic, file I/O, and string methods together in a practical data- processing task.