156 commands · 9 cheat sheets · Python
Data and Serialization master quick reference
Browse 156 commands from 9 focused cheat sheets on page 1 of 1. Each example opens its matching detailed section.
Data and Serialization · 19 commands
Python bytes, bytearray, memoryview, and Binary Data Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create literal bytes | payload = b'GET / HTTP/1.1\r\n' | View examples |
| Create bytes from integers | payload = bytes([0, 127, 255]) | View examples |
| Encode Unicode text | payload = text.encode('utf-8') | View examples |
| Read one byte value | value = payload[0] | View examples |
| Copy a byte range | header = payload[:4] | View examples |
| Find a byte marker | offset = payload.find(b'\r\n') | View examples |
| Create a mutable copy | buffer = bytearray(payload) | View examples |
| Replace one byte | buffer[offset] = value | View examples |
| Append binary data | buffer.extend(chunk) | View examples |
| Create a buffer view | view = memoryview(buffer) | View examples |
| Create a read-only view | readonly = view.toreadonly() | View examples |
| Release a view | view.release() | View examples |
| Cast bytes to elements | words = memoryview(buffer).cast('H') | View examples |
| Materialize view values | values = view.tolist() | View examples |
| Pack a portable header | header = struct.pack('!HI', version, length) | View examples |
| Unpack exact-size data | version, length = struct.unpack('!HI', header) | View examples |
| Unpack at an offset | values = struct.unpack_from('!HI', buffer, offset) | View examples |
| Render hexadecimal bytes | text = payload.hex(sep=' ') | View examples |
| Parse hexadecimal text | payload = bytes.fromhex(text) | View examples |
Data and Serialization · 16 commands
Python Dates, Times, and Time Zones Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a calendar date | day = date(2026, 8, 12) | View examples |
| Move by elapsed days | tomorrow = day + timedelta(days=1) | View examples |
| Combine date and time | meeting = datetime.combine(day, time(9, 30)) | View examples |
| Read the current UTC instant | now = datetime.now(UTC) | View examples |
| Construct an aware datetime | instant = datetime(2026, 8, 12, 15, tzinfo=UTC) | View examples |
| Convert the same instant | local = instant.astimezone(target_zone) | View examples |
| Parse ISO-formatted text | value = datetime.fromisoformat('2026-08-12T15:30:00+00:00') | View examples |
| Emit ISO-formatted text | text = value.isoformat(timespec='seconds') | View examples |
| Parse a declared format | value = datetime.strptime(text, '%Y-%m-%d %H:%M') | View examples |
| Format for display | label = value.strftime('%Y-%m-%d %H:%M') | View examples |
| Load an IANA time zone | zone = ZoneInfo('America/Sao_Paulo') | View examples |
| Decode a POSIX timestamp | instant = datetime.fromtimestamp(timestamp, tz=UTC) | View examples |
| Advance a local schedule | next_run = local_run + timedelta(days=1) | View examples |
| Measure elapsed time | elapsed = end.astimezone(UTC) - start.astimezone(UTC) | View examples |
| Read a duration in seconds | seconds = duration.total_seconds() | View examples |
| Disambiguate a repeated wall time | later = local.replace(fold=1) | View examples |
Data and Serialization · 17 commands
Python Decimal, Fractions, and Numeric Precision Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Compare floats approximately | same = math.isclose(actual, expected, rel_tol=1e-9, abs_tol=0.0) | View examples |
| Sum floats accurately | total = math.fsum(values) | View examples |
| Inspect an exact float ratio | numerator, denominator = value.as_integer_ratio() | View examples |
| Construct from decimal text | price = Decimal('19.95') | View examples |
| Convert an existing float exactly | value = Decimal.from_float(binary_value) | View examples |
| Set local precision | with localcontext() as ctx: ctx.prec = 12 | View examples |
| Trap inexact arithmetic | ctx.traps[Inexact] = True | View examples |
| Round to a fixed exponent | amount = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) | View examples |
| Multiply then add once | result = value.fma(multiplier, addend) | View examples |
| Construct an exact fraction | ratio = Fraction(3, 8) | View examples |
| Parse a decimal fraction | ratio = Fraction('0.125') | View examples |
| Approximate with a bounded denominator | ratio = Fraction(value).limit_denominator(1000) | View examples |
| Calculate an arithmetic mean | average = statistics.fmean(values) | View examples |
| Calculate a median | middle = statistics.median(values) | View examples |
| Calculate sample spread | spread = statistics.stdev(values) | View examples |
| Round with Python's built-in policy | rounded = round(value, ndigits) | View examples |
| Format fixed decimal places | text = f'{value:.2f}' | View examples |
Data and Serialization · 16 commands
Python JSON, CSV, and Data Interchange Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Encode a JSON string | text = json.dumps(value) | View examples |
| Decode a JSON string | value = json.loads(text) | View examples |
| Use interoperable value types | payload = {'ok': True, 'items': [1, 2], 'note': None} | View examples |
| Pretty-print deterministically | text = json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) | View examples |
| Emit compact JSON | text = json.dumps(value, separators=(',', ':'), ensure_ascii=False) | View examples |
| Encode to a text stream | json.dump(value, stream) | View examples |
| Decode from a stream | value = json.load(stream) | View examples |
| Encode a custom type | text = json.dumps(value, default=encode_custom) | View examples |
| Transform decoded objects | value = json.loads(text, object_hook=decode_custom) | View examples |
| Parse decimals exactly | value = json.loads(text, parse_float=Decimal) | View examples |
| Reject non-finite output | text = json.dumps(value, allow_nan=False) | View examples |
| Inspect object key pairs | value = json.loads(text, object_pairs_hook=reject_duplicates) | View examples |
| Read CSV rows | rows = csv.reader(stream, delimiter=',') | View examples |
| Write CSV rows | writer = csv.writer(stream, lineterminator='\n') | View examples |
| Read named CSV fields | rows = csv.DictReader(stream) | View examples |
| Write named CSV fields | writer = csv.DictWriter(stream, fieldnames=['name', 'note']) | View examples |
Data and Serialization · 18 commands
Python pickle, shelve, and Persistent Objects Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Serialize to bytes | payload = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL) | View examples |
| Load trusted bytes | value = pickle.loads(payload) | View examples |
| Write a pickle file | with open(path, 'wb') as stream: pickle.dump(value, stream, protocol=5) | View examples |
| Read the newest protocol | protocol = pickle.HIGHEST_PROTOCOL | View examples |
| Target protocol 4 | payload = pickle.dumps(value, protocol=4) | View examples |
| Read the default protocol | protocol = pickle.DEFAULT_PROTOCOL | View examples |
| Customize serialized state | def __getstate__(self):
return {'version': 1, 'value': self.value} | View examples |
| Restore validated state | def __setstate__(self, state):
self.value = validate(state) | View examples |
| Define a reduction | def __reduce__(self): return (type(self), (self.value,)) | View examples |
| Register a type reducer | copyreg.pickle(ValueType, reduce_value) | View examples |
| Use a private reducer table | pickler.dispatch_table = {ValueType: reduce_value} | View examples |
| Emit an external identifier | def persistent_id(self, obj): return ('Record', obj.key) | View examples |
| Resolve an external identifier | def persistent_load(self, pid):
return repository.fetch(pid) | View examples |
| Open a shelf | with shelve.open(path, flag='c', writeback=False) as db: use(db) | View examples |
| Persist a mutable update | value = db[key]; value.append(item); db[key] = value | View examples |
| Synchronize a shelf | db.sync() | View examples |
| Disassemble without loading | python -m pickletools payload.pickle | View examples |
| Override global resolution | def find_class(self, module, name):
raise pickle.UnpicklingError('globals forbidden') | View examples |
Data and Serialization · 20 commands
Python Random Sampling and Statistics Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a local generator | rng = random.Random(seed) | View examples |
| Capture generator state | state = rng.getstate() | View examples |
| Restore generator state | rng.setstate(state) | View examples |
| Draw from range semantics | value = rng.randrange(start, stop, step) | View examples |
| Choose one element | item = rng.choice(population) | View examples |
| Sample without replacement | items = rng.sample(population, k=3) | View examples |
| Sample by relative weight | draws = rng.choices(population, weights=weights, k=100) | View examples |
| Draw a uniform float | value = rng.uniform(low, high) | View examples |
| Draw from a normal model | value = rng.normalvariate(mu, sigma) | View examples |
| Generate random bytes | token = secrets.token_bytes(32) | View examples |
| Generate a URL-safe token | token = secrets.token_urlsafe(32) | View examples |
| Choose securely | character = secrets.choice(alphabet) | View examples |
| Compute an arithmetic mean | center = statistics.mean(values) | View examples |
| Compute a median | center = statistics.median(values) | View examples |
| Find all most-common values | modes = statistics.multimode(values) | View examples |
| Estimate sample spread | spread = statistics.stdev(sample) | View examples |
| Measure population spread | spread = statistics.pstdev(population) | View examples |
| Compute linear correlation | coefficient = statistics.correlation(xs, ys) | View examples |
| Estimate sample quartiles | cuts = statistics.quantiles(values, n=4, method='exclusive') | View examples |
| Summarize observed endpoints | cuts = statistics.quantiles(values, n=4, method='inclusive') | View examples |
Data and Serialization · 13 commands
Python Regular Expressions Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Compile a pattern | pattern = re.compile(r'\d{4}-\d{2}-\d{2}') | View examples |
| Search anywhere | match = pattern.search(text) | View examples |
| Match from start | match = pattern.match(text) | View examples |
| Validate the whole string | match = pattern.fullmatch(text) | View examples |
| Capture a group | value = match.group(1) | View examples |
| Named capture | r'(?P<year>\d{4})-(?P<month>\d{2})' | View examples |
| Non-capturing group | r'(?:https?|ftp)://' | View examples |
| Iterate matches | for match in pattern.finditer(text): print(match.span()) | View examples |
| Collect matches | values = pattern.findall(text) | View examples |
| Split by pattern | parts = re.split(r'\s*,\s*', text) | View examples |
| Replace matches | clean = re.sub(r'\s+', ' ', text).strip() | View examples |
| Verbose pattern | pattern = re.compile(r'''...''', re.VERBOSE) | View examples |
| Ignore case | pattern = re.compile(r'error', re.IGNORECASE) | View examples |
Data and Serialization · 17 commands
Python Text Encoding and Unicode Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Encode UTF-8 | payload = text.encode('utf-8') | View examples |
| Decode UTF-8 | text = payload.decode('utf-8') | View examples |
| Use strict decoding | text = payload.decode('utf-8', errors='strict') | View examples |
| Open UTF-8 text | with open(path, 'r', encoding='utf-8') as stream: text = stream.read() | View examples |
| Write stable LF newlines | with open(path, 'w', encoding='utf-8', newline='\n') as stream: stream.write(text) | View examples |
| Wrap a binary stream | text_stream = io.TextIOWrapper(binary_stream, encoding='utf-8', newline='') | View examples |
| Normalize canonical composition | normalized = unicodedata.normalize('NFC', text) | View examples |
| Check normalization | ok = unicodedata.is_normalized('NFC', text) | View examples |
| Build a caseless key | key = unicodedata.normalize('NFC', text).casefold() | View examples |
| Lowercase for presentation | lowered = text.lower() | View examples |
| Read a code point | number = ord(character) | View examples |
| Create a character | character = chr(number) | View examples |
| Read a Unicode name | name = unicodedata.name(character, 'UNNAMED') | View examples |
| Replace malformed input | text = payload.decode('utf-8', errors='replace') | View examples |
| Preserve OS bytes | text = payload.decode(filesystem_encoding, errors='surrogateescape') | View examples |
| Create a streaming decoder | decoder = codecs.getincrementaldecoder('utf-8')(errors='strict') | View examples |
| Finish a decode stream | tail = decoder.decode(b'', final=True) | View examples |
Data and Serialization · 20 commands
Python XML Parsing and Generation Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Parse an XML value | root = ET.fromstring(xml_bytes) | View examples |
| Parse an XML file | tree = ET.parse(path) | View examples |
| Catch malformed XML | except ET.ParseError as error: report(error.position) | View examples |
| Create an expanded name | tag = '{urn:books}title' | View examples |
| Query with a prefix map | items = root.findall('b:item', {'b': 'urn:books'}) | View examples |
| Choose a serialization prefix | ET.register_namespace('b', 'urn:books') | View examples |
| Find one matching element | item = root.find('./item[@id="a"]') | View examples |
| Find matching elements | items = root.findall('.//item') | View examples |
| Iterate matching descendants | for item in root.iter('item'): consume(item) | View examples |
| Append a child element | child = ET.SubElement(parent, 'item', {'id': item_id}) | View examples |
| Set element text | child.text = value | View examples |
| Remove a child | parent.remove(child) | View examples |
| Serialize to text | xml_text = ET.tostring(root, encoding='unicode') | View examples |
| Write UTF-8 XML | tree.write(path, encoding='utf-8', xml_declaration=True) | View examples |
| Canonicalize XML | canonical = ET.canonicalize(xml_data=xml_text) | View examples |
| Iterate completed elements | events = ET.iterparse(source, events=('end',)) | View examples |
| Release processed content | element.clear() | View examples |
| Create a pull parser | parser = ET.XMLPullParser(events=('start', 'end')) | View examples |
| Inspect the Expat version | version = pyexpat.EXPAT_VERSION | View examples |
| Bound XML input bytes | if len(xml_bytes) > MAX_XML_BYTES: raise ValueError('XML too large') | View examples |



