Quick reference for Python developers — 100+ snippets
Showing all commands
x = 10x, y, z = 1, 2, 3type(x)isinstance(x, int)int("42")str(42)float("3.14")bool(0) # Falseinput("Enter: ")print(f"Hello {name}")s.upper()s.lower()s.strip()s.split(",")",".join(lst)s.replace("old", "new")s.find("sub")s.startswith("pre")s.endswith(".py")s[1:5]s[::-1]len(s)s.isdigit()s.title()lst = [1, 2, 3]lst.append(4)lst.insert(0, "first")lst.remove(2)lst.pop()lst.pop(0)lst.sort()sorted(lst)lst.reverse()lst.index(2)lst.count(2)lst.extend([4, 5])[x**2 for x in range(10)][x for x in lst if x > 2]lst[::2]d = {"key": "value"}d["key"]d.get("key", "default")d["new_key"] = "val"del d["key"]d.keys()d.values()d.items()d.update({"a": 1})d.pop("key")"key" in d{k: v for k, v in d.items()}d | {"new": 1}s = {1, 2, 3}s.add(4)s.discard(2)s1 | s2s1 & s2s1 - s2t = (1, 2, 3)a, b, c = ta, *rest = (1,2,3,4)if x > 0: ... elif x == 0: ... else: ...for item in iterable:for i, val in enumerate(lst):for k, v in d.items():while condition:breakcontinuex if condition else ymatch value: case 1: ... case _: ...def func(a, b=10):def func(*args, **kwargs):lambda x: x * 2def func() -> int:def func(x: str, y: int = 0):map(func, iterable)filter(func, iterable)from functools import reduce@decoratorclass Dog:
def __init__(self, name):
self.name = nameclass Puppy(Dog):super().__init__()@property@staticmethod@classmethoddef __str__(self):def __len__(self):from dataclasses import dataclass
@dataclass
class Point:
x: float
y: floatwith open("f.txt") as f:
text = f.read()with open("f.txt") as f:
lines = f.readlines()with open("f.txt", "w") as f:
f.write("text")with open("f.txt", "a") as f:
f.write("more")import json
with open("d.json") as f:
data = json.load(f)json.dumps(data, indent=2)import csv
with open("d.csv") as f:
reader = csv.reader(f)from pathlib import Path
p = Path("dir/file.txt")Path("dir").mkdir(exist_ok=True)list(Path(".").glob("*.py"))try:
risky()
except ValueError as e:
print(e)except (TypeError, KeyError):finally:raise ValueError("msg")assert x > 0, "x must be positive"class MyError(Exception): passimport osfrom os import pathimport numpy as npfrom . import moduleif __name__ == "__main__":pip install packagepip freeze > requirements.txtpython -m venv envlen(obj)range(start, stop, step)zip(lst1, lst2)any(iterable)all(iterable)min(iterable) / max(iterable)sum(iterable)abs(-5)round(3.14159, 2)dir(obj)help(func)import datetime
datetime.datetime.now()import re
re.findall(r"\d+", text)import os
os.environ.get("KEY")import sys
sys.argvfrom collections import Counter
Counter(lst)from collections import defaultdict
dd = defaultdict(list)import itertools
itertools.chain(a, b)import random
random.choice(lst)import hashlib
hashlib.sha256(b"text").hexdigest()import subprocess
subprocess.run(["ls", "-la"])