Python Cheatsheet

Strings

Use this Python reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

String Literals and Creation

s = "double quotes"
s = 'single quotes'
s = """triple
double"""
s = '''triple
single'''
s = r"raw \n (not a newline)"     # raw: no escape processing
s = b"bytes literal"              # bytes, not str
s = f"formatted {1 + 1}"         # f-string (3.6+)
s = rb"raw bytes \n"              # raw bytes

# Implicit concatenation (compile-time only)
s = "Hello, " "World"             # "Hello, World"

# str() constructor
str(42)         # "42"
str(3.14)       # "3.14"
str(None)       # "None"
str(b"bytes")   # "b'bytes'"

# Multiline with backslash continuation
s = "first line " \
    "second line"

Indexing and Slicing

s = "Hello, World!"

s[0]       # 'H'
s[-1]      # '!'
s[7:12]    # 'World'
s[:5]      # 'Hello'
s[7:]      # 'World!'
s[::-1]    # '!dlroW ,olleH'  (reversed)
s[::2]     # 'Hlo ol!'        (every other char)

String Methods — Searching

MethodDescriptionExample
find(sub, start, end)Index of first occurrence, -1 if not found"hello".find("ll") → 2
rfind(sub, start, end)Index of last occurrence, -1 if not found"hello".rfind("l") → 3
index(sub, start, end)Like find but raises ValueError"hello".index("e") → 1
rindex(sub, start, end)Like rfind but raises ValueError
count(sub, start, end)Count non-overlapping occurrences"banana".count("an") → 2
startswith(prefix, start, end)True if starts with prefix"hello".startswith("he")
endswith(suffix, start, end)True if ends with suffix"hello".endswith("lo")
in operatorSubstring check"ell" in "hello" → True
# startswith/endswith accept tuples of prefixes
"hello".startswith(("he", "hi", "ho"))  # True
"main.py".endswith((".py", ".pyw"))     # True

String Methods — Transformation

MethodDescriptionExample
lower()Lowercase"Hello".lower() → "hello"
upper()Uppercase"Hello".upper() → "HELLO"
title()Title case"hello world".title() → "Hello World"
capitalize()First letter upper, rest lower"hELLO".capitalize() → "Hello"
swapcase()Swap upper/lower"hElLo".swapcase() → "HeLlO"
casefold()Aggressive lowercase (Unicode)"ß".casefold() → "ss"
strip(chars)Remove leading/trailing chars" hi ".strip() → "hi"
lstrip(chars)Remove leading chars" hi".lstrip() → "hi"
rstrip(chars)Remove trailing chars"hi ".rstrip() → "hi"
replace(old, new, count)Replace occurrences"aaa".replace("a", "b", 2) → "bba"
expandtabs(tabsize)Replace \t with spaces"a\tb".expandtabs(4) → "a b"
encode(encoding, errors)Encode to bytes"hi".encode("utf-8")
removeprefix(prefix)Remove exact prefix (3.9+)"test_foo".removeprefix("test_")
removesuffix(suffix)Remove exact suffix (3.9+)"report.csv".removesuffix(".csv")

String Methods — Splitting and Joining

MethodDescriptionExample
split(sep, maxsplit)Split on sep (default: whitespace)"a,b,c".split(",") → ["a","b","c"]
rsplit(sep, maxsplit)Split from right"a.b.c".rsplit(".", 1) → ["a.b","c"]
splitlines(keepends)Split on line boundaries"a\nb".splitlines() → ["a","b"]
join(iterable)Join strings with separator",".join(["a","b","c"]) → "a,b,c"
partition(sep)Split into (before, sep, after)"a=b".partition("=") → ("a","=","b")
rpartition(sep)Split from right"a=b=c".rpartition("=") → ("a=b","=","c")
# split with maxsplit
"one two three four".split(" ", 2)  # ['one', 'two', 'three four']

# join — MUST join strings; convert if needed
", ".join(str(x) for x in [1, 2, 3])  # "1, 2, 3"
"\n".join(lines)

# splitlines handles \n, \r\n, \r, \v, \f, \x1c, \x1d, \x1e, \x85, 
, 


String Methods — Testing / Classification

MethodDescription
isalpha()All alphabetic characters
isdigit()All digit characters (0-9)
isnumeric()All numeric characters (includes Unicode numerals)
isdecimal()All decimal digit characters
isalnum()All alphanumeric
isspace()All whitespace
islower()All cased chars are lowercase
isupper()All cased chars are uppercase
istitle()Title-cased
isidentifier()Valid Python identifier
isprintable()All printable characters
isascii()All ASCII (code points 0–127)
"abc".isalpha()    # True
"123".isdigit()    # True
"abc123".isalnum() # True
"  \t\n".isspace() # True
"Hello World".istitle()   # True
"hello".islower()  # True
"HELLO".isupper()  # True

String Formatting

f-strings (recommended)

name, age = "Alice", 30
f"Name: {name}, Age: {age}"

# Format spec: {value:format_spec}
f"{3.14159:.2f}"          # "3.14"      — 2 decimal places
f"{1000000:,}"            # "1,000,000" — thousands separator
f"{42:05d}"               # "00042"     — zero-pad to width 5
f"{42:>10}"               # "        42" — right-align in 10
f"{42:<10}"               # "42        " — left-align
f"{'hi':^10}"             # "    hi    " — center
f"{255:#x}"               # "0xff"      — hex with prefix
f"{255:#b}"               # "0b11111111" — binary with prefix
f"{255:#o}"               # "0o377"     — octal with prefix
f"{0.001:.2e}"            # "1.00e-03"  — scientific
f"{val!r}"                # repr(val)
f"{val!s}"                # str(val)
f"{val!a}"                # ascii(val)

# Nested expressions
f"{'yes' if condition else 'no'}"
f"{d['key']}"
f"{obj.attr}"
f"{func(arg)}"
f"{{literal braces}}"     # "literal braces" (escaped)

str.format()

"{} and {}".format("one", "two")
"{0} and {1}".format("one", "two")          # positional
"{name} is {age}".format(name="Alice", age=30)  # keyword
"{:.2f}".format(3.14159)                    # "3.14"
"{:>10}".format("right")                    # right-align

% formatting (legacy)

"Hello, %s! You are %d years old." % ("Alice", 30)
"%.2f" % 3.14159     # "3.14"
"%05d" % 42          # "00042"

format() built-in

format(3.14159, ".2f")    # "3.14"
format(42, "08b")         # "00101010"
format(255, "x")          # "ff"

String Alignment and Padding

s = "hello"
s.ljust(10)           # "hello     "
s.rjust(10)           # "     hello"
s.center(11)          # "   hello   "
s.ljust(10, "-")      # "hello-----"
s.zfill(10)           # "00000hello" (zero-pad; honors leading sign)

Character Operations

ord("A")       # 65  — char to Unicode code point
chr(65)        # 'A' — code point to char

# Iterate over characters
for ch in "hello":
    print(ch)

# Characters are just strings of length 1
"a" < "b"    # True  (lexicographic)

Encoding / Decoding

# str → bytes
"hello".encode("utf-8")           # b'hello'
"café".encode("utf-8")            # b'caf\xc3\xa9'
"café".encode("latin-1")
"café".encode("utf-8", errors="ignore")
"café".encode("ascii", errors="replace")   # b'caf?'
"café".encode("ascii", errors="xmlcharrefreplace")  # b'caf&#233;'

# bytes → str
b"hello".decode("utf-8")          # 'hello'
b"\xff\xfe".decode("utf-16")

# Common encodings: utf-8, ascii, latin-1, utf-16, utf-32, cp1252

Regular Expressions

import re

# Compile for reuse
pattern = re.compile(r"\d{3}-\d{4}")

# Search functions
re.match(r"\d+", text)          # match at beginning only
re.search(r"\d+", text)         # first match anywhere
re.findall(r"\d+", text)        # list of all matches (strings)
re.finditer(r"\d+", text)       # iterator of match objects
re.fullmatch(r"\d+", text)      # entire string must match
re.sub(r"\d+", "NUM", text)     # replace all matches
re.sub(r"\d+", "NUM", text, count=1)  # replace first
re.subn(r"\d+", "NUM", text)    # (new_string, count)
re.split(r"\s+", text)          # split on pattern

# Match object
m = re.search(r"(\d+)-(\w+)", text)
m.group()      # entire match
m.group(1)     # first capturing group
m.group(2)     # second capturing group
m.groups()     # all groups as tuple
m.groupdict()  # named groups as dict
m.start()      # start index
m.end()        # end index
m.span()       # (start, end)

# Named groups
m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})", text)
m.group("year")
m.groupdict()  # {'year': '2024', 'month': '01'}

# Flags
re.search(r"hello", text, re.IGNORECASE)
re.search(r"hello", text, re.I | re.M)  # combine flags
# re.I = IGNORECASE, re.M = MULTILINE, re.S = DOTALL, re.X = VERBOSE

String Templates

from string import Template

t = Template("Hello, $name! You have $count messages.")
t.substitute(name="Alice", count=3)    # raises KeyError if missing
t.safe_substitute(name="Alice")        # leaves $count as-is

textwrap Module

import textwrap

textwrap.wrap("long text...", width=40)        # list of wrapped lines
textwrap.fill("long text...", width=40)        # single wrapped string
textwrap.dedent("""
    indented
    text
""")                                           # remove common leading whitespace
textwrap.indent("text\nmore", "    ")          # add prefix to each line
textwrap.shorten("very long text...", width=20, placeholder=" [...]")