TetSharing

Python string methods cheat sheet

Strings are immutable, so every method below returns a new string (or another value) and leaves the original alone. Results are shown as Python would display them with repr(), so strings appear in quotes. New to strings? Start with the strings lesson and f-strings.

Change caseSearchTest the contentSplit and joinTrim and padReplace, format, misc

Change case

SyntaxWhat it doesExample → result
s.upper()Copy with all letters uppercase"Hello".upper()
→ 'HELLO'
s.lower()Copy with all letters lowercase"Hello".lower()
→ 'hello'
s.title()Capitalize the first letter of each word"hello world".title()
→ 'Hello World'
s.capitalize()First character uppercase, the rest lowercase"hELLO".capitalize()
→ 'Hello'
s.swapcase()Swap upper and lower case"PyThon".swapcase()
→ 'pYtHON'
s.casefold()Aggressive lowercase for case-insensitive comparison"Straße".casefold()
→ 'strasse'
SyntaxWhat it doesExample → result
s.find(sub)Index of the first match, or -1"banana".find("an")
→ 1
s.rfind(sub)Index of the last match, or -1"banana".rfind("an")
→ 3
s.index(sub)Like find(), but raises ValueError when missing"banana".index("n")
→ 2
s.count(sub)Number of non-overlapping occurrences"banana".count("a")
→ 3
s.startswith(prefix)True if s starts with prefix (a tuple tests several)"report.csv".startswith("rep")
→ True
s.endswith(suffix)True if s ends with suffix"report.csv".endswith((".csv", ".tsv"))
→ True
sub in sSubstring membership test"nan" in "banana"
→ True

Test the content

SyntaxWhat it doesExample → result
s.isdigit()All characters are digits"2026".isdigit()
→ True
s.isalpha()All characters are letters"abc1".isalpha()
→ False
s.isalnum()All characters are letters or digits"abc1".isalnum()
→ True
s.isspace()All characters are whitespace" \t".isspace()
→ True
s.isupper()All cased characters are uppercase"ABC".isupper()
→ True

Split and join

SyntaxWhat it doesExample → result
s.split(sep)List of pieces between separators"a,b,,c".split(",")
→ ['a', 'b', '', 'c']
s.split()Split on runs of whitespace, dropping empty pieces" one two ".split()
→ ['one', 'two']
s.split(sep, maxsplit)Split at most maxsplit times"k=v=w".split("=", 1)
→ ['k', 'v=w']
s.rsplit(sep, maxsplit)Split from the right"a.b.c".rsplit(".", 1)
→ ['a.b', 'c']
s.splitlines()Split at line boundaries"l1\nl2".splitlines()
→ ['l1', 'l2']
sep.join(iterable)Glue strings together with sep between them"-".join(["a", "b", "c"])
→ 'a-b-c'
s.partition(sep)Split once into (before, sep, after)"user@example.com".partition("@")
→ ('user', '@', 'example.com')

Trim and pad

SyntaxWhat it doesExample → result
s.strip()Remove whitespace from both ends" hi ".strip()
→ 'hi'
s.strip(chars)Remove any of the given characters from both ends"xxhixx".strip("x")
→ 'hi'
s.rstrip() / s.lstrip()Remove whitespace from one end" hi ".rstrip()
→ ' hi'
s.removeprefix(p)Drop a leading prefix if present (Python 3.9+)"v1.2".removeprefix("v")
→ '1.2'
s.removesuffix(x)Drop a trailing suffix if present (Python 3.9+)"file.txt".removesuffix(".txt")
→ 'file'
s.center(width, fill)Center in a field of the given width"hi".center(6, "*")
→ '**hi**'
s.ljust(width)Left-align by padding on the right"hi".ljust(4) + "|"
→ 'hi |'
s.rjust(width)Right-align by padding on the left"7".rjust(3)
→ ' 7'
s.zfill(width)Pad with leading zeros"42".zfill(5)
→ '00042'

Replace, format, misc

SyntaxWhat it doesExample → result
s.replace(old, new)Replace every occurrence"a-b-c".replace("-", "+")
→ 'a+b+c'
s.replace(old, new, count)Replace only the first count occurrences"a-b-c".replace("-", "+", 1)
→ 'a+b-c'
s.format(*args)Fill {} placeholders"{} has {} items".format("Cart", 3)
→ 'Cart has 3 items'
f"{value:spec}"f-string with a format specifierf"{3.14159:.2f}"
→ '3.14'
len(s)Number of characterslen("héllo")
→ 5
s[::-1]Reversed copy via slicing"abc"[::-1]
→ 'cba'

Official docs

Compiled by Ethan Cole (pen name) with AI-assisted drafting; every example in the table is executed by our test suite. Related lessons: strings, f strings.