Python

Python String Methods Cheatsheet

Quick reference for Python string methods including split, join, strip, replace, format, f-strings, and common string operations.

Creating Strings

s = "hello"
s = 'hello'
s = """multi
line"""
s = str(42)                         # "42"
s = r"raw\nstring"                  # No escape processing
s = b"bytes"                        # Bytes literal

Searching

MethodReturnsDescription
s.find(sub, start?, end?)intFirst index or -1
s.rfind(sub)intLast index or -1
s.index(sub)intFirst index or raises ValueError
s.rindex(sub)intLast index or raises ValueError
s.count(sub)intNumber of occurrences
s.startswith(prefix)boolStarts with prefix
s.endswith(suffix)boolEnds with suffix
sub in sboolContains substring
"hello world".find("world")          # 6
"hello world".count("l")            # 3
"hello".startswith("hel")           # True
"world" in "hello world"            # True

Case Conversion

MethodDescriptionExample
s.upper()All uppercase"HELLO"
s.lower()All lowercase"hello"
s.capitalize()First char upper"Hello"
s.title()Title case"Hello World"
s.swapcase()Swap case"hELLO"
s.casefold()Aggressive lowercase (for comparison)"straße" -> "strasse"

Trimming & Padding

MethodDescription
s.strip()Remove whitespace both ends
s.strip(chars)Remove specific chars both ends
s.lstrip()Remove leading whitespace
s.rstrip()Remove trailing whitespace
s.ljust(width, fill?)Left-justify, pad right
s.rjust(width, fill?)Right-justify, pad left
s.center(width, fill?)Center, pad both sides
s.zfill(width)Pad with zeros on left
"  hello  ".strip()                  # "hello"
"xxhelloxx".strip("x")              # "hello"
"42".zfill(5)                       # "00042"
"hi".center(10, "-")                # "----hi----"

Splitting & Joining

"a,b,c".split(",")                  # ["a", "b", "c"]
"a,b,c".split(",", 1)              # ["a", "b,c"] (maxsplit)
"a b  c".split()                    # ["a", "b", "c"] (split on whitespace)
"line1\nline2".splitlines()         # ["line1", "line2"]
"a.b.c".rsplit(".", 1)             # ["a.b", "c"]
"a.b.c".partition(".")             # ("a", ".", "b.c")
"a.b.c".rpartition(".")            # ("a.b", ".", "c")

",".join(["a", "b", "c"])           # "a,b,c"
" ".join(["hello", "world"])        # "hello world"

Replacing

"hello".replace("l", "r")           # "herro"
"hello".replace("l", "r", 1)        # "herlo" (count)

# For regex replacement
import re
re.sub(r"\d+", "#", "abc 123")      # "abc #"

Testing

MethodDescription
s.isalpha()All alphabetic
s.isdigit()All digits
s.isalnum()All alphanumeric
s.isspace()All whitespace
s.isupper()All uppercase
s.islower()All lowercase
s.istitle()Title case
s.isnumeric()All numeric (includes unicode)
s.isascii()All ASCII characters
s.isidentifier()Valid Python identifier
s.isprintable()All printable characters

f-Strings (Python 3.6+)

name = "Alice"
age = 30

f"Hello, {name}!"                   # "Hello, Alice!"
f"{age + 1}"                        # "31"
f"{name!r}"                         # "'Alice'" (repr)
f"{name!s}"                         # "Alice" (str)
f"{3.14159:.2f}"                    # "3.14"
f"{42:05d}"                         # "00042"
f"{1000:,}"                         # "1,000"
f"{0.75:.0%}"                       # "75%"
f"{'hi':>10}"                       # "        hi"
f"{'hi':<10}"                       # "hi        "
f"{'hi':^10}"                       # "    hi    "
f"{'hi':*^10}"                      # "****hi****"
f"{value = }"                       # "value = 42" (debug, 3.8+)

Format Spec Mini-Language

SpecDescriptionExample
dIntegerf"{42:d}" -> "42"
fFixed-pointf"{3.14:.1f}" -> "3.1"
eScientificf"{1234:.2e}" -> "1.23e+03"
%Percentagef"{0.75:.0%}" -> "75%"
,Thousands separatorf"{1000:,}" -> "1,000"
_Underscore separatorf"{1000:_}" -> "1_000"
xHex (lowercase)f"{255:x}" -> "ff"
XHex (uppercase)f"{255:X}" -> "FF"
oOctalf"{8:o}" -> "10"
bBinaryf"{10:b}" -> "1010"

Slicing

s = "hello world"
s[0]                                 # "h"
s[-1]                                # "d"
s[0:5]                               # "hello"
s[6:]                                # "world"
s[::-1]                              # "dlrow olleh" (reverse)
s[::2]                               # "hlowrd" (every 2nd char)

Common Recipes

# Reverse a string
s[::-1]

# Check palindrome
s == s[::-1]

# Remove prefix/suffix (3.9+)
s.removeprefix("http://")
s.removesuffix(".txt")

# Translate characters
table = str.maketrans("abc", "xyz")
"abc".translate(table)               # "xyz"

# Multiline string dedent
from textwrap import dedent
dedent("""
    hello
    world
""").strip()