env.dev

Python Cheat Sheet — Quick Reference

Python quick reference: data types, string methods, list/dict comprehensions, f-strings, file I/O, and common standard library modules.

Last updated:

A quick reference for Python syntax and standard library essentials. Covers data types, string methods, comprehensions, f-strings, file I/O, and commonly used stdlib modules.

Data Types

TypeExampleNotes
intx = 42Arbitrary precision integers
floatx = 3.1464-bit double precision
strx = 'hello'Immutable Unicode text
boolx = TrueSubclass of int (True=1, False=0)
listx = [1, 2, 3]Mutable ordered sequence
tuplex = (1, 2, 3)Immutable ordered sequence
dictx = {'a': 1}Mutable key-value mapping
setx = {1, 2, 3}Mutable unordered unique elements
Nonex = NoneSingleton null value

String Methods

MethodDescription
s.strip()Remove leading/trailing whitespace
s.split(sep)Split into list by separator
sep.join(iterable)Join iterable with separator
s.replace(old, new)Replace all occurrences
s.startswith(prefix)Check if string starts with prefix
s.endswith(suffix)Check if string ends with suffix
s.upper() / s.lower()Convert case
s.find(sub)Return index of substring or -1
s.count(sub)Count non-overlapping occurrences

List & Dict Comprehensions

SyntaxDescription
[x for x in iterable]Basic list comprehension
[x for x in iterable if cond]Filtered list comprehension
[f(x) for x in iterable]Transform each element
{k: v for k, v in items}Dict comprehension
{x for x in iterable}Set comprehension
[x for row in matrix for x in row]Nested / flatten comprehension
{k: v for k, v in d.items() if v}Filtered dict comprehension

F-Strings & Formatting

SyntaxDescription
f'{name}'Variable interpolation
f'{x + y}'Expression evaluation
f'{value:.2f}'Float with 2 decimal places
f'{num:,}'Number with thousand separators
f'{text:>20}'Right-align in 20-char field
f'{text:<20}'Left-align in 20-char field
f'{num:08d}'Zero-pad integer to 8 digits
f'{val!r}'Use repr() instead of str()

File I/O

PatternDescription
open('f.txt')Open file for reading (default mode='r')
open('f.txt', 'w')Open file for writing (truncates)
open('f.txt', 'a')Open file for appending
open('f.txt', 'rb')Open file in binary read mode
with open('f') as fh:Context manager (auto-closes)
fh.read()Read entire file as string
fh.readlines()Read all lines into a list
fh.write(text)Write string to file
fh.writelines(lines)Write list of strings to file

os & sys

FunctionDescription
os.getcwd()Get current working directory
os.listdir(path)List directory contents
os.path.join(a, b)Join path components
os.path.exists(path)Check if path exists
os.environ["KEY"]Access environment variable
os.makedirs(path, exist_ok=True)Create nested directories
sys.argvCommand-line arguments list
sys.exit(code)Exit with status code

json Module

FunctionDescription
json.dumps(obj)Serialize object to JSON string
json.dumps(obj, indent=2)Pretty-print JSON string
json.loads(s)Parse JSON string to object
json.dump(obj, fh)Write JSON to file handle
json.load(fh)Read JSON from file handle
json.dumps(obj, default=str)Custom serializer for unsupported types

re (Regular Expressions)

FunctionDescription
re.search(pattern, s)Find first match anywhere in string
re.match(pattern, s)Match only at beginning of string
re.findall(pattern, s)Return all non-overlapping matches
re.sub(pattern, repl, s)Replace all matches
re.split(pattern, s)Split string by pattern
re.compile(pattern)Compile pattern for reuse
m.group()Get matched text from match object
m.groups()Get all captured groups as tuple

Frequently Asked Questions

What Python version does this cheat sheet cover?

This cheat sheet covers Python 3.10+ syntax including match statements, f-strings, and modern type hints.

What are list comprehensions in Python?

List comprehensions are a concise way to create lists: [x**2 for x in range(10)]. They can include conditions: [x for x in range(10) if x % 2 == 0].

What is the difference between a list and a tuple?

Lists are mutable (can be modified) and use square brackets []. Tuples are immutable (cannot be changed after creation) and use parentheses (). Tuples are faster and can be used as dictionary keys.