Skip to main content

59 entries · 7 sections

Python String Methods Cheat Sheet

Python's built-in string methods grouped by job — case, trimming, searching, splitting, replacing, testing and formatting — with the behaviour that surprises people spelled out, such as what strip() actually strips and why title() mangles apostrophes.

Changing case

SyntaxWhat it does
s.lower()A lower-cased copy.
s.upper()An upper-cased copy.
s.title()Title Cases Each Word. It also mangles apostrophes: "don't" becomes "Don'T".
s.capitalize()First character upper-cased, everything else lower-cased.
s.swapcase()Swap the case of every character.
s.casefold()Aggressive lower-casing for caseless comparison. It handles cases lower() cannot, such as German ss.

Trimming and padding

SyntaxWhat it does
s.strip()Remove whitespace from both ends.
s.lstrip() / s.rstrip()Trim the left / right end only.
s.strip("/#")Remove any of those characters from both ends. It is a character set, not a substring.
s.removeprefix("api/")Drop an exact prefix if it is there (Python 3.9+). This is what people wrongly expect strip to do.
s.removesuffix(".txt")Drop an exact suffix if it is there (3.9+).
s.ljust(10, ".") / s.rjust(10)Pad to a width on the right / on the left.
s.center(20, "-")Pad on both sides.
s.zfill(5)Pad with leading zeros, keeping any leading sign in front.
s.expandtabs(4)Replace tab characters with spaces to the given tab width.

Searching

SyntaxWhat it does
"a" in sThe idiomatic containment test, and the one to reach for first.
s.find("x")The index of the first occurrence, or -1 when it is absent.
s.rfind("x")The index of the last occurrence, or -1.
s.index("x")Like find, but raises ValueError instead of returning -1.
s.count("x")How many non-overlapping occurrences there are.
s.startswith("http")Prefix test. It also accepts a tuple, so one call can test several prefixes.
s.endswith((".png", ".jpg"))Suffix test with several options at once.

Splitting and joining

SyntaxWhat it does
s.split()Split on any run of whitespace and discard the empty pieces.
s.split(",")Split on a separator. An empty string gives [''], not an empty list.
s.split(",", 2)Split at most twice, leaving the remainder of the string intact.
s.rsplit(",", 1)Split from the right — how you take the last field cleanly.
s.splitlines()Split on line boundaries, without the trailing empty piece that split("\n") produces.
s.partition("=")Return (before, separator, after) — a clean key/value split that never raises.
s.rpartition("=")The same, splitting at the last separator.
", ".join(items)Join an iterable of strings. The separator goes first, and every item must already be a string.
s[::-1]Reverse a string. Slicing, not a method, but it is what everyone uses.

Replacing and encoding

SyntaxWhat it does
s.replace("a", "b")Replace every occurrence.
s.replace("a", "b", 1)Replace only the first occurrence.
s.translate(str.maketrans("abc", "xyz"))Map characters one-to-one in a single pass. Much faster than chained replaces.
s.translate(str.maketrans("", "", "aeiou"))Delete a whole set of characters.
s.encode("utf-8")Convert a str to bytes.
b.decode("utf-8")Convert bytes back to a str.
s.encode("ascii", "ignore")Encode, silently dropping the characters that will not fit.

Testing the content

SyntaxWhat it does
s.isdigit()Every character is a digit, and the string is not empty.
s.isnumeric()Wider than isdigit: it also accepts fractions and other numeric characters.
s.isdecimal()The narrowest of the three: only characters that can form a base-10 number.
s.isalpha()Letters only.
s.isalnum()Letters and digits only.
s.isspace()Whitespace only.
s.islower() / s.isupper()Case tests. Both are False for a string containing no cased letters at all.
s.istitle()Every word starts with an upper-case letter.
s.isidentifier()Valid as a Python name. Pair it with keyword.iskeyword() for a full check.
s.isascii()Every character is ASCII (3.7+).
s.isprintable()Contains no non-printable characters.

Formatting

SyntaxWhat it does
f"{name} is {age}"An f-string. The default way to build a string since Python 3.6.
f"{value:.2f}"Two decimal places.
f"{n:,}"Thousands separators. Use _ instead of , for underscores.
f"{n:>10}" / f"{n:<10}" / f"{n:^10}"Right, left and centre aligned in a ten-character field.
f"{n:08.3f}"Zero-padded to eight characters with three decimal places.
f"{ratio:.1%}"Formatted as a percentage, so 0.256 becomes 25.6%.
f"{x=}"Prints x=<value> — a debugging shortcut added in 3.8.
f"{obj!r}"Use repr() instead of str() for the value.
"{} and {}".format(a, b)The older format method. Still useful when the template is stored separately from the values.
textwrap.dedent(s)Strip the common leading indentation from a triple-quoted block.

Worth knowing

  • s.strip("abc") does not remove the substring "abc" — it removes any of the characters a, b and c from both ends until it hits something else. To remove an exact prefix or suffix, use removeprefix and removesuffix, added in Python 3.9 precisely because this was such a common bug.
  • Strings are immutable, so every method here returns a new string and none of them modify s in place. Writing s.upper() on its own line does nothing at all; you have to assign the result. It is also why building a string in a loop with += is quadratic, and why "".join(parts) is the correct pattern.
  • For anything beyond a fixed separator, reach for the re module rather than chaining replaces. re.sub(r"\s+", " ", s) collapses all whitespace in one pass, and re.split handles multi-character or alternative separators that str.split cannot express.

Try a snippet instead of reading about it

Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.

Open the editor

Python String Methods — common questions

What is the difference between split() and split(" ")?
split() with no argument splits on any run of whitespace — spaces, tabs and newlines — and discards empty results, so "a b".split() gives ['a', 'b']. split(" ") splits on each single space individually and keeps the empties, so the same input gives ['a', '', 'b']. For parsing human-typed text, the no-argument form is nearly always what you want.
How do I remove a prefix or suffix from a string?
Use s.removeprefix("api/") and s.removesuffix(".txt"), both added in Python 3.9. Before that the idiom was s[len(prefix):] if s.startswith(prefix) else s. Do not use strip for this — it treats its argument as a set of characters to remove, not as a substring.
What is the difference between find() and index()?
They do the same search, but find() returns -1 when the substring is absent while index() raises a ValueError. Use find when a missing match is normal and you will branch on the result; use index when a missing match is a bug and you want it to stop the program. If you only need to know whether it is there, "x" in s is clearer than both.
How do I format a number with commas or a fixed number of decimals?
Use an f-string format specification: f"{n:,}" adds thousands separators, f"{n:.2f}" fixes two decimal places, and f"{n:,.2f}" does both. For percentages, f"{ratio:.1%}" multiplies by 100 and appends the sign, and for locale-aware output use the locale module or babel rather than string formatting.