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
| Type | Example | Notes |
|---|---|---|
| int | x = 42 | Arbitrary precision integers |
| float | x = 3.14 | 64-bit double precision |
| str | x = 'hello' | Immutable Unicode text |
| bool | x = True | Subclass of int (True=1, False=0) |
| list | x = [1, 2, 3] | Mutable ordered sequence |
| tuple | x = (1, 2, 3) | Immutable ordered sequence |
| dict | x = {'a': 1} | Mutable key-value mapping |
| set | x = {1, 2, 3} | Mutable unordered unique elements |
| None | x = None | Singleton null value |
String Methods
| Method | Description |
|---|---|
| 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
| Syntax | Description |
|---|---|
| [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
| Syntax | Description |
|---|---|
| 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
| Pattern | Description |
|---|---|
| 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
| Function | Description |
|---|---|
| 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.argv | Command-line arguments list |
| sys.exit(code) | Exit with status code |
json Module
| Function | Description |
|---|---|
| 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)
| Function | Description |
|---|---|
| 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 |