Programming2025-12-01

Python 3.x Complete Cheatsheet

A concise reference for Python 3.x covering string formatting, data types, built-in functions, file handling, and core language concepts including generators, decorators, and async/await.

#Python#Programming#Reference

String Formatting

f-strings (Python 3.6+)

The recommended approach for string formatting in modern Python.

code
name = "Alice"
age = 30
f"Hello, {name}! You are {age} years old."
f"{3.14159:.2f}"          # format spec: 2 decimal places → '3.14'
f"{1000000:,}"            # thousands separator → '1,000,000'
f"{'left':<10}"           # left-align in 10 chars
f"{'right':>10}"          # right-align in 10 chars
f"{'center':^10}"         # center in 10 chars
f"{255:#x}"               # hex with prefix → '0xff'
f"{value!r}"              # repr()
f"{value!s}"              # str()
f"{value!a}"              # ascii()

str.format()

code
"Hello, {}!".format("Alice")
"Hello, {name}!".format(name="Alice")
"{0} + {1} = {2}".format(1, 2, 3)
"{:.2f}".format(3.14159)

% Formatting (old-style)

code
"Hello, %s!" % "Alice"
"Pi is %.2f" % 3.14159
"%d items at $%.2f each" % (5, 1.99)
SpecifierMeaning
%sString
%dInteger
%fFloat
%xHex
%oOctal
%eScientific notation

Template strings

code
from string import Template
t = Template("Hello, $name!")
t.substitute(name="Alice")
t.safe_substitute(name="Alice")  # won't raise on missing keys

textwrap helpers

code
import textwrap
textwrap.dedent(text)         # remove common leading whitespace
textwrap.indent(text, "  ")   # add prefix to each line
textwrap.wrap(text, width=70) # wrap to list of lines
textwrap.fill(text, width=70) # wrap to single string

String Methods

Case

MethodDescription
s.upper()All uppercase
s.lower()All lowercase
s.title()Title Case
s.capitalize()First char upper, rest lower
s.swapcase()Swap upper/lower
s.casefold()Aggressive lowercase (for comparisons)

Search and Test

MethodDescription
s.find(sub)Index of first occurrence, or -1
s.rfind(sub)Index of last occurrence, or -1
s.index(sub)Like find but raises ValueError
s.count(sub)Count non-overlapping occurrences
s.startswith(prefix)Returns bool
s.endswith(suffix)Returns bool
s.isalpha()All alphabetic?
s.isdigit()All digits?
s.isalnum()All alphanumeric?
s.isspace()All whitespace?
s.islower()All lowercase?
s.isupper()All uppercase?

Modify and Transform

MethodDescription
s.strip()Remove leading/trailing whitespace
s.lstrip()Remove leading whitespace
s.rstrip()Remove trailing whitespace
s.replace(old, new)Replace all occurrences
s.replace(old, new, n)Replace first n occurrences
s.encode(enc)Encode to bytes

Split and Join

MethodDescription
s.split()Split on whitespace
s.split(sep)Split on separator
s.splitlines()Split on line boundaries
sep.join(iterable)Join iterable with separator
s.partition(sep)Split into (before, sep, after)

Padding and Alignment

MethodDescription
s.center(width)Center-pad with spaces
s.ljust(width)Left-justify, pad right
s.rjust(width)Right-justify, pad left
s.zfill(width)Pad with zeros on left

Misc

MethodDescription
s.removeprefix(prefix)Remove prefix if present (3.9+)
s.removesuffix(suffix)Remove suffix if present (3.9+)
s.maketrans(x, y)Create translation table
s.translate(table)Apply translation table

Python Data Types

Numeric

TypeDescriptionExample
intWhole numbers, unlimited precision42, 0xFF, 0b101
floatFloating point (64-bit)3.14, 1e10
complexComplex numbers3+4j
boolBoolean, subclass of intTrue, False

Sequences

TypeMutable?DescriptionExample
strNoImmutable text"hello"
listYesOrdered, mixed types[1, "a", 3.0]
tupleNoImmutable ordered collection(1, 2, 3)
rangeNoLazy sequence of integersrange(0, 10, 2)
bytesNoImmutable byte sequenceb"hello"
bytearrayYesMutable byte sequencebytearray(b"hello")

Mappings and Sets

TypeMutable?DescriptionExample
dictYesKey-value pairs, ordered (3.7+){"a": 1}
setYesUnique, unordered items{1, 2, 3}
frozensetNoImmutable setfrozenset({1, 2})

Iterator and Collection Methods

list

MethodDescription
l.append(x)Add item to end
l.extend(iterable)Extend with iterable
l.insert(i, x)Insert at index
l.remove(x)Remove first occurrence
l.pop(i=-1)Remove and return item at index
l.sort(key=None, reverse=False)Sort in-place
l.reverse()Reverse in-place
l.copy()Shallow copy

dict

MethodDescription
d.get(key, default)Get value or default
d.keys()View of keys
d.values()View of values
d.items()View of (key, value) pairs
d.update(other)Merge another dict
d.pop(key, default)Remove and return value
d.setdefault(key, default)Get or set default
d.copy()Shallow copy
dict.fromkeys(keys, value)New dict from keys

set

MethodDescription
s.add(x)Add element
s.remove(x)Remove x (raises if missing)
s.discard(x)Remove x (no error if missing)
s.union(other)Items in either set
s.intersection(other)Items in both sets
s.difference(other)Items in s but not other
s.symmetric_difference(other)Items in one but not both
s.issubset(other)Is s a subset of other?
s.issuperset(other)Is s a superset of other?

bytes and bytearray

code
b"hello".hex()
bytes.fromhex("68656c6c6f")
b"hello".decode("utf-8")
"hello".encode("utf-8")

Built-in Functions

Type and Identity

FunctionDescription
type(obj)Return type of object
isinstance(obj, type)Check instance type
issubclass(cls, parent)Check class hierarchy
id(obj)Unique identity integer
hash(obj)Hash value

Type Conversion

FunctionDescription
int(x)Convert to integer
float(x)Convert to float
str(x)Convert to string
bool(x)Convert to bool
list(x)Convert to list
tuple(x)Convert to tuple
set(x)Convert to set
dict(**kwargs)Create dict
chr(i)Integer to Unicode character
ord(c)Character to Unicode code point
hex(n)Integer to hex string
bin(n)Integer to binary string

Math and Numeric

FunctionDescription
abs(x)Absolute value
round(x, n)Round to n decimal places
pow(x, y)x raised to y
divmod(a, b)(quotient, remainder) tuple
max(iterable)Maximum value
min(iterable)Minimum value
sum(iterable)Sum of items

Iteration and Sequences

FunctionDescription
len(obj)Length of object
range(start, stop, step)Lazy integer sequence
enumerate(iterable, start=0)(index, value) pairs
zip(*iterables)Pair elements from iterables
map(fn, iterable)Apply function to each item
filter(fn, iterable)Keep items where fn is truthy
sorted(iterable, key, reverse)Return sorted list
reversed(seq)Reverse iterator
any(iterable)True if any item is truthy
all(iterable)True if all items are truthy

Built-in Packages

Utilities

ModuleDescription
osOS interaction: paths, env vars, processes
sysPython runtime, argv, stdin/stdout/stderr
pathlibObject-oriented filesystem paths
shutilHigh-level file operations
loggingFlexible logging system
argparseCommand-line argument parsing
functoolsHigher-order functions
itertoolsEfficient iteration tools
typingType hints
dataclasses@dataclass decorator
contextlibContext manager utilities

Math and Data

ModuleDescription
mathMath functions (sqrt, pi, floor, etc.)
decimalDecimal fixed-point arithmetic
statisticsMean, median, stdev, etc.
randomRandom number generation

Data Formats

ModuleDescription
jsonJSON encoding/decoding
csvCSV file reading/writing
base64Base16/32/64 encoding
hashlibMD5, SHA, etc. hashing
picklePython object serialization
sqlite3SQLite database interface

Networking

ModuleDescription
urllib.requestOpen URLs
urllib.parseParse URLs and query strings
socketLow-level networking
sslTLS/SSL wrapper

Concurrency

ModuleDescription
threadingThread-based parallelism
multiprocessingProcess-based parallelism
concurrent.futuresHigh-level thread/process pool
asyncioAsync I/O event loop
subprocessSpawn subprocesses

File Handling

Opening Files

code
open(file, mode='r', encoding=None, errors=None)
ModeDescription
'r'Read (default)
'w'Write (truncate)
'a'Append
'x'Exclusive create (fails if exists)
'b'Binary mode
'+'Read and write

Context Manager

code
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()

File Object Methods

MethodDescription
f.read(size=-1)Read all or up to size bytes
f.readline()Read one line
f.readlines()Read all lines into a list
f.write(s)Write string or bytes
f.seek(offset, whence=0)Move to position
f.tell()Current position
f.close()Close file

Common Patterns

code
# Read all lines without newlines
with open("file.txt") as f:
    lines = f.read().splitlines()

# Iterate line by line (memory efficient)
with open("file.txt") as f:
    for line in f:
        print(line.strip())

# Write multiple lines
with open("file.txt", "w") as f:
    f.writelines(f"{line}\n" for line in data)

pathlib (preferred over os.path)

code
from pathlib import Path

p = Path("file.txt")
p.read_text(encoding="utf-8")
p.write_text("content")
p.exists()
p.is_file()
p.unlink()
p.rename("new.txt")
p.mkdir(parents=True, exist_ok=True)
list(p.glob("*.py"))
p.stat().st_size
p.parent / p.stem / p.suffix

Core Python Concepts

Variables and Assignment

code
x = 10
a, b, c = 1, 2, 3
a, *rest = [1, 2, 3, 4]
x, y = y, x              # swap values

Control Flow

code
if x > 0:
    ...
elif x == 0:
    ...
else:
    ...

value = "yes" if condition else "no"

# match (3.10+)
match command:
    case "quit":
        ...
    case "go" | "move":
        ...
    case _:
        ...

Loops

code
for item in iterable:
    if condition: continue
    if condition: break
else:
    # runs if loop did not break
    ...

Functions

code
def func(pos, /, normal, *, kw_only, key=default, **kwargs):
    """Docstring."""
    return value

fn = lambda x, y: x + y

def greet(name: str) -> str:
    return f"Hello, {name}"

Comprehensions

code
[x*2 for x in range(10) if x % 2 == 0]       # list
{x: x**2 for x in range(5)}                   # dict
{x for x in range(5)}                         # set
(x*2 for x in range(10))                      # generator

Classes

code
class Animal:
    class_var = "shared"

    def __init__(self, name):
        self.name = name

    def speak(self):
        ...

    @classmethod
    def create(cls, name):
        return cls(name)

    @staticmethod
    def info():
        ...

    @property
    def label(self):
        return self.name.upper()

class Dog(Animal):
    def speak(self):
        super().speak()

Common Dunder Methods

MethodTriggered by
__init__(self)Object creation
__str__(self)str(obj), print(obj)
__repr__(self)repr(obj), REPL display
__len__(self)len(obj)
__getitem__(self, key)obj[key]
__contains__(self, item)item in obj
__iter__(self)iter(obj)
__call__(self, ...)obj(...)
__enter__ / __exit__with obj:
__eq__, __lt__, etc.==, <, etc.
__hash__(self)hash(obj)
__bool__(self)bool(obj)

Exceptions

code
try:
    risky()
except ValueError as e:
    handle(e)
except (TypeError, KeyError):
    ...
else:
    # runs if no exception
    ...
finally:
    # always runs
    ...

raise ValueError("message")

class MyError(Exception):
    def __init__(self, msg):
        super().__init__(msg)

Common Built-in Exceptions

ExceptionWhen raised
ValueErrorWrong value type or content
TypeErrorWrong argument type
KeyErrorMissing dict key
IndexErrorSequence index out of range
AttributeErrorMissing attribute
NameErrorUndefined variable
ImportErrorModule not found
FileNotFoundErrorFile does not exist
PermissionErrorPermission denied
ZeroDivisionErrorDivision by zero
RecursionErrorMax recursion depth exceeded
AssertionErrorassert statement failed

Generators

code
def count_up(n):
    for i in range(n):
        yield i

gen = count_up(5)
next(gen)       # 0
list(gen)       # [1, 2, 3, 4]

squares = (x**2 for x in range(10))

def chain(*iters):
    for it in iters:
        yield from it

Decorators

code
import functools

def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("before")
        result = func(*args, **kwargs)
        print("after")
        return result
    return wrapper

@my_decorator
def hello():
    print("hello")

def repeat(n):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(n):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def hi():
    print("hi")

Context Managers

code
from contextlib import contextmanager

@contextmanager
def managed_resource():
    setup()
    try:
        yield resource
    finally:
        teardown()

class ManagedResource:
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        cleanup()
        return False

Async and Await

code
import asyncio

async def fetch_data():
    await asyncio.sleep(1)
    return "data"

async def main():
    result = await fetch_data()
    tasks = [asyncio.create_task(fetch_data()) for _ in range(3)]
    results = await asyncio.gather(*tasks)

asyncio.run(main())

Type Hints

code
from typing import Optional, Union, List, Dict

def func(x: int, y: float = 1.0) -> str: ...
def f(items: list[int]) -> dict[str, int]: ...   # 3.9+ built-in generics
def f(val: int | None) -> str | None: ...        # 3.10+ union syntax

Common functools Tools

ToolDescription
functools.lru_cache(maxsize)Memoize function results
functools.cacheUnbounded memoization (3.9+)
functools.partial(fn, *args)Pre-fill function arguments
functools.reduce(fn, iterable)Left-fold reduction
functools.wraps(fn)Preserve function metadata in decorators
functools.cached_propertyLazy attribute computed once

Common itertools Tools

ToolDescription
chain(*iters)Chain iterables together
cycle(iter)Repeat iterable endlessly
islice(iter, n)Slice an iterator
takewhile(pred, iter)Take while predicate is true
groupby(iter, key)Group consecutive elements
zip_longest(*iters)Zip, fill shorter with None
product(*iters)Cartesian product
permutations(iter, r)All permutations
combinations(iter, r)All combinations
accumulate(iter, fn)Running totals or reductions

Walrus Operator (3.8+)

code
if n := len(data):
    print(f"List has {n} items")

while chunk := f.read(8192):
    process(chunk)

__name__ Guard

code
if __name__ == "__main__":
    main()

Runs only when the file is executed directly, not when imported as a module.

Slots

code
class Point:
    __slots__ = ("x", "y")
    def __init__(self, x, y):
        self.x, self.y = x, y

Restricts instance attributes and reduces per-instance memory overhead.