Skip to content

Python string methods

Strings are immutable, so every method returns a new string (or a list/bool/int). Run any example to see the output.

25 entries

Case

print("hello world".upper(), "HeLLo".lower())

upper() / lower().

print("hello world".title(), "hello world".capitalize())

title() capitalises each word, capitalize() only the first.

print("Straße".casefold() == "STRASSE".casefold())

casefold() for case-insensitive comparison.

print("Hello".swapcase())

swapcase().

Split & join

print("a,b,,c".split(","))

split(sep) keeps empty strings between separators.

print("  many   spaces here ".split())

split() with no argument splits on runs of whitespace.

print("k=v=w".split("=", 1), "k=v=w".rsplit("=", 1))

maxsplit from the left or right.

print("line1\nline2\r\nline3".splitlines())

splitlines() handles \n and \r\n.

print("-".join(["2026", "09", "27"]))

join() glues an iterable of strings.

print("user@example.com".partition("@"))

partition() → (before, sep, after).

Trim & pad

print(repr("  hi \n".strip()), repr("xxhixx".strip("x")))

strip() removes whitespace or given chars from both ends.

print("v1.2".removeprefix("v"), "report.csv".removesuffix(".csv"))

removeprefix / removesuffix (3.9+).

print("7".zfill(3), "hi".center(8, "*"), "hi".ljust(5) + "|")

Padding.

Search & replace

s = "banana"
print(s.find("an"), s.rfind("an"), s.find("x"))

find returns index or -1.

s = "banana"
print(s.count("a"), "nan" in s)

count() and the in operator.

print("photo.JPG".lower().endswith((".jpg", ".png")))

startswith/endswith accept a tuple.

print("a-b-c".replace("-", "+"), "a-b-c".replace("-", "+", 1))

replace(old, new, count).

Checks

print("123".isdigit(), "12.5".isdigit(), "abc".isalpha(), "abc1".isalnum())

Character-class checks (isdigit is False for "12.5").

print("   ".isspace(), "Hello World".istitle(), "abc".islower())

More checks.

print("my_var".isidentifier())

Valid Python identifier?

Formatting

name, n = "Ada", 3
print(f"{name} has {n} items")

f-string (preferred).

print("{} + {} = {}".format(1, 2, 3))

str.format().

print(f"{0.4567:.1%}", f"{42:>6}", f"{255:#x}")

Format specs: percent, alignment, hex.

print("tab\tsep".expandtabs(4))

expandtabs().

table = str.maketrans("abc", "xyz")
print("aabbcc".translate(table))

translate() maps characters.

Frequently asked questions

How do I reverse a string in Python?

Use slicing: s[::-1]. There is no reverse() method on strings because they are immutable.

Why doesn’t s.replace() change my string?

Strings are immutable. replace() returns a new string, so assign it: s = s.replace("a", "b").

split() vs split(" ")?

split() splits on any run of whitespace and drops empty strings. split(" ") splits on each single space and keeps empty strings when there are consecutive spaces.

Related cheat sheets