Python’s str type is immutable, so every method here returns a new string
rather than changing the original. The methods cover case conversion, searching,
splitting and joining, trimming, testing, and encoding. This is a searchable
offline reference.
Method groups
Because strings are immutable, a call like s.upper() produces a new string — you must assign it (s = s.upper()) to keep the result. The methods fall into six groups:
- Case —
upper,lower,title,capitalize,casefold,swapcase. - Search —
find,index,count,startswith,endswith.findreturns-1on failure;indexraisesValueError. - Split / join —
split,rsplit,splitlines,partition,join. - Trim / pad —
strip,lstrip,rstrip,removeprefix,removesuffix,center,ljust,rjust,zfill. - Test —
isalpha,isdigit,isalnum,isspace,isidentifier, etc. - Transform —
replace,translate,format,format_map,encode.
Worked examples
" Hello, World ".strip().lower().replace(",", "")
# -> 'hello world'
"file.tar.gz".removesuffix(".gz") # -> 'file.tar'
"report_2026_q1.csv".split("_") # -> ['report', '2026', 'q1.csv']
", ".join(["apples", "oranges", "pears"]) # -> 'apples, oranges, pears'
"$19.99".lstrip("$") # strips any leading $, or any char in the set
strip vs removeprefix / removesuffix
This is the most common source of subtle bugs with string trimming:
"file.py".rstrip(".py") # -> 'fil' (removes p, y, . individually — WRONG)
"file.py".removesuffix(".py") # -> 'file' (removes exact suffix — CORRECT)
strip, lstrip, and rstrip interpret their argument as a set of characters to remove, not a literal prefix or suffix. Each character in the argument is stripped from the relevant end as long as it matches. Use removeprefix and removesuffix (Python 3.9+) whenever you want to remove an exact string.
split and join: complementary operations
split breaks a string into a list; join reassembles a list into a string. Note that join is called on the separator, not the list:
parts = "a,b,c".split(",") # -> ['a', 'b', 'c']
"|".join(parts) # -> 'a|b|c'
split() with no argument splits on any whitespace and drops empty strings — useful for normalizing ragged input. split(",") keeps empty strings between consecutive delimiters.
find vs index
Both locate the first occurrence of a substring and return its position as an integer. The difference matters only on failure:
"hello".find("z") # -> -1 (no exception)
"hello".index("z") # raises ValueError
Use find when absence is expected and you want to test the result with if pos != -1. Use index when absence is a genuine error that should surface immediately.
Notes
str.joinis called on the separator:", ".join(items).casefold()is more aggressive thanlower()for case-insensitive comparison of non-ASCII text (e.g., the Germanßfolds toss).- This reference covers the standard
strmethods. For exact version availability consult the official Python docs.