String methods
Overview
Text arrives messy: extra spaces, random capitals, values separated by commas, lines that need checking. Python’s str type has dozens of methods that handle these jobs in a single call. This lesson covers the ones you’ll use every week.
Remember: methods return new strings
Strings can’t change (Strings), so every method gives you a new string:
name = " asha "
name.strip() # returns 'asha' — but name is unchanged
name = name.strip() # keep the resultCleaning and changing case
" hi ".strip() # 'hi' both ends
" hi ".lstrip() # 'hi ' left only
" hi ".rstrip() # ' hi' right only — great for line endings
"xxhixx".strip("x") # 'hi' strip specific characters
"Hello".lower() # 'hello'
"Hello".upper() # 'HELLO'
"ada lovelace".title() # 'Ada Lovelace'
"hello world".capitalize() # 'Hello world'
"Hello".swapcase() # 'hELLO'
"Straße".casefold() # 'strasse' — stronger lower() for comparing textFor case-insensitive comparison, compare normalised versions: a.lower() == b.lower() (or casefold() for international text).
removeprefix and removesuffix remove an exact piece from one end — unlike strip, which removes any of the given characters:
"report.csv".removesuffix(".csv") # 'report'
"Mr Smith".removeprefix("Mr ") # 'Smith'Searching
s = "Hello, World"
"World" in s # True
s.startswith("Hell") # True
s.endswith((".com", ".org")) # a tuple checks several options at once
s.find("o") # 4 — first position, or -1 if not found
s.find("z") # -1
s.index("z") # ValueError — like find but raises an error
s.count("l") # 3
s.rfind("o") # 8 — search from the rightReplacing
"I like tea".replace("tea", "coffee") # 'I like coffee'
"a-b-c".replace("-", "") # 'abc'
"aaa".replace("a", "b", 2) # 'bba' — at most 2 replacementsSplitting and joining
These two are partners, and probably the most useful methods of all.
split breaks a string into a list:
"the quick brown fox".split() # ['the', 'quick', 'brown', 'fox']
"tea,coffee,,cake".split(",") # ['tea', 'coffee', '', 'cake']
"2026-12-04".split("-") # ['2026', '12', '04']
"a=1=2".split("=", 1) # ['a', '1=2'] — split at most once
"line one\nline two".splitlines() # ['line one', 'line two']With no argument, split() splits on any run of whitespace and ignores spaces at the ends. With an argument, it splits on exactly that text, so empty items can appear.
join glues a list of strings together, with the string you call it on between the items:
", ".join(["tea", "coffee", "cake"]) # 'tea, coffee, cake'
"".join(["a", "b", "c"]) # 'abc'
"\n".join(lines) # one item per linejoin only accepts strings: ", ".join([1, 2]) is a TypeError. Convert first: ", ".join(str(n) for n in numbers).
A neat trick combining both — squash repeated spaces:
" ".join("too many spaces".split()) # 'too many spaces'Testing characters
These return True or False for the whole string (and False for an empty string):
| Method | True when every character is… |
|---|---|
isdigit() |
a digit (0–9) |
isalpha() |
a letter |
isalnum() |
a letter or digit |
isspace() |
whitespace |
isupper() / islower() |
upper / lower case (ignoring non-letters) |
"2026".isdigit() # True
"12.5".isdigit() # False — the dot isn't a digit
"Asha".isalpha() # True
"R2D2".isalnum() # TruePadding
"7".zfill(3) # '007'
"tea".center(9, "*") # '***tea***'
"tea".ljust(6) + "|" # 'tea |'For aligning output, f-string format specifiers (next lesson) are usually neater.
Chaining
Because each method returns a string, you can chain them:
email = " Asha.Rao@Example.COM ".strip().lower()
slug = title.lower().replace(" ", "-")Keep chains short enough to read; split long ones over several lines with intermediate variables.
Cheat sheet: clean with
strip/lower, test within/startswith, change withreplace, and take apart and put together withsplitandjoin.
Clean up a contact list
Each line of the raw text is a messy name ; email ; city record. For each non-blank line: split it on ;, strip spaces from each part, title-case the name, lower-case the email, and upper-case the city. Skip (and count) records whose email doesn’t contain exactly one @ or doesn’t end with .com or .org. Print each clean record as Name <email> (CITY), then the number skipped. Finally, make a URL slug from the title " Python Basics: Strings & Text! " → python-basics-strings-text (lower case; keep only letters, digits and spaces; then join the words with hyphens).
raw = """
asha RAO ; Asha.Rao@Example.com ; pune
ben jones; ben@@mail.org ; leeds
chen li ; CHEN@uni.org; Beijing
dee ; dee@site.net ; lagos
"""
# Clean the records
# Make the slug
title = " Python Basics: Strings & Text! "raw = """
asha RAO ; Asha.Rao@Example.com ; pune
ben jones; ben@@mail.org ; leeds
chen li ; CHEN@uni.org; Beijing
dee ; dee@site.net ; lagos
"""
# Clean the records
skipped = 0
for line in raw.splitlines():
if not line.strip():
continue
name, email, city = [part.strip() for part in line.split(";")]
name = " ".join(name.split()).title() # also squashes repeated spaces
email = email.lower()
if email.count("@") != 1 or not email.endswith((".com", ".org")):
skipped += 1
continue
print(f"{name} <{email}> ({city.upper()})")
print("Skipped:", skipped)
# Make the slug
title = " Python Basics: Strings & Text! "
kept = "".join(ch for ch in title.lower() if ch.isalnum() or ch == " ")
slug = "-".join(kept.split())
print(slug) # python-basics-strings-textSummary
- Methods return new strings — assign the result (
s = s.strip()) to keep it. strip,lower,upper,titleandreplaceclean and normalise text.split()breaks text into a list (on whitespace by default);"sep".join(list)glues a list back together.in,startswith,endswith,findandcountsearch text;startswithandendswithaccept a tuple of options.isdigit,isalpha,isalnum,isspaceand friends test what kind of characters a string contains.