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)
| Specifier | Meaning |
|---|---|
%s | String |
%d | Integer |
%f | Float |
%x | Hex |
%o | Octal |
%e | Scientific 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
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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
| Type | Description | Example |
|---|---|---|
int | Whole numbers, unlimited precision | 42, 0xFF, 0b101 |
float | Floating point (64-bit) | 3.14, 1e10 |
complex | Complex numbers | 3+4j |
bool | Boolean, subclass of int | True, False |
Sequences
| Type | Mutable? | Description | Example |
|---|---|---|---|
str | No | Immutable text | "hello" |
list | Yes | Ordered, mixed types | [1, "a", 3.0] |
tuple | No | Immutable ordered collection | (1, 2, 3) |
range | No | Lazy sequence of integers | range(0, 10, 2) |
bytes | No | Immutable byte sequence | b"hello" |
bytearray | Yes | Mutable byte sequence | bytearray(b"hello") |
Mappings and Sets
| Type | Mutable? | Description | Example |
|---|---|---|---|
dict | Yes | Key-value pairs, ordered (3.7+) | {"a": 1} |
set | Yes | Unique, unordered items | {1, 2, 3} |
frozenset | No | Immutable set | frozenset({1, 2}) |
Iterator and Collection Methods
list
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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
| Function | Description |
|---|---|
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
| Function | Description |
|---|---|
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
| Function | Description |
|---|---|
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
| Function | Description |
|---|---|
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
| Module | Description |
|---|---|
os | OS interaction: paths, env vars, processes |
sys | Python runtime, argv, stdin/stdout/stderr |
pathlib | Object-oriented filesystem paths |
shutil | High-level file operations |
logging | Flexible logging system |
argparse | Command-line argument parsing |
functools | Higher-order functions |
itertools | Efficient iteration tools |
typing | Type hints |
dataclasses | @dataclass decorator |
contextlib | Context manager utilities |
Math and Data
| Module | Description |
|---|---|
math | Math functions (sqrt, pi, floor, etc.) |
decimal | Decimal fixed-point arithmetic |
statistics | Mean, median, stdev, etc. |
random | Random number generation |
Data Formats
| Module | Description |
|---|---|
json | JSON encoding/decoding |
csv | CSV file reading/writing |
base64 | Base16/32/64 encoding |
hashlib | MD5, SHA, etc. hashing |
pickle | Python object serialization |
sqlite3 | SQLite database interface |
Networking
| Module | Description |
|---|---|
urllib.request | Open URLs |
urllib.parse | Parse URLs and query strings |
socket | Low-level networking |
ssl | TLS/SSL wrapper |
Concurrency
| Module | Description |
|---|---|
threading | Thread-based parallelism |
multiprocessing | Process-based parallelism |
concurrent.futures | High-level thread/process pool |
asyncio | Async I/O event loop |
subprocess | Spawn subprocesses |
File Handling
Opening Files
code
open(file, mode='r', encoding=None, errors=None)
| Mode | Description |
|---|---|
'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
| Method | Description |
|---|---|
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
| Method | Triggered 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
| Exception | When raised |
|---|---|
ValueError | Wrong value type or content |
TypeError | Wrong argument type |
KeyError | Missing dict key |
IndexError | Sequence index out of range |
AttributeError | Missing attribute |
NameError | Undefined variable |
ImportError | Module not found |
FileNotFoundError | File does not exist |
PermissionError | Permission denied |
ZeroDivisionError | Division by zero |
RecursionError | Max recursion depth exceeded |
AssertionError | assert 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
| Tool | Description |
|---|---|
functools.lru_cache(maxsize) | Memoize function results |
functools.cache | Unbounded 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_property | Lazy attribute computed once |
Common itertools Tools
| Tool | Description |
|---|---|
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.