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

Open full cheat sheet
UseSyntaxExamples
Create literal bytespayload = b'GET / HTTP/1.1\r\n'View examples
Create bytes from integerspayload = bytes([0, 127, 255])View examples
Encode Unicode textpayload = text.encode('utf-8')View examples
Read one byte valuevalue = payload[0]View examples
Copy a byte rangeheader = payload[:4]View examples
Find a byte markeroffset = payload.find(b'\r\n')View examples
Create a mutable copybuffer = bytearray(payload)View examples
Replace one bytebuffer[offset] = valueView examples
Append binary databuffer.extend(chunk)View examples
Create a buffer viewview = memoryview(buffer)View examples
Create a read-only viewreadonly = view.toreadonly()View examples
Release a viewview.release()View examples
Cast bytes to elementswords = memoryview(buffer).cast('H')View examples
Materialize view valuesvalues = view.tolist()View examples
Pack a portable headerheader = struct.pack('!HI', version, length)View examples
Unpack exact-size dataversion, length = struct.unpack('!HI', header)View examples
Unpack at an offsetvalues = struct.unpack_from('!HI', buffer, offset)View examples
Render hexadecimal bytestext = payload.hex(sep=' ')View examples
Parse hexadecimal textpayload = bytes.fromhex(text)View examples

Data and Serialization · 16 commands

Python Dates, Times, and Time Zones Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a calendar dateday = date(2026, 8, 12)View examples
Move by elapsed daystomorrow = day + timedelta(days=1)View examples
Combine date and timemeeting = datetime.combine(day, time(9, 30))View examples
Read the current UTC instantnow = datetime.now(UTC)View examples
Construct an aware datetimeinstant = datetime(2026, 8, 12, 15, tzinfo=UTC)View examples
Convert the same instantlocal = instant.astimezone(target_zone)View examples
Parse ISO-formatted textvalue = datetime.fromisoformat('2026-08-12T15:30:00+00:00')View examples
Emit ISO-formatted texttext = value.isoformat(timespec='seconds')View examples
Parse a declared formatvalue = datetime.strptime(text, '%Y-%m-%d %H:%M')View examples
Format for displaylabel = value.strftime('%Y-%m-%d %H:%M')View examples
Load an IANA time zonezone = ZoneInfo('America/Sao_Paulo')View examples
Decode a POSIX timestampinstant = datetime.fromtimestamp(timestamp, tz=UTC)View examples
Advance a local schedulenext_run = local_run + timedelta(days=1)View examples
Measure elapsed timeelapsed = end.astimezone(UTC) - start.astimezone(UTC)View examples
Read a duration in secondsseconds = duration.total_seconds()View examples
Disambiguate a repeated wall timelater = local.replace(fold=1)View examples

Data and Serialization · 17 commands

Python Decimal, Fractions, and Numeric Precision Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Compare floats approximatelysame = math.isclose(actual, expected, rel_tol=1e-9, abs_tol=0.0)View examples
Sum floats accuratelytotal = math.fsum(values)View examples
Inspect an exact float rationumerator, denominator = value.as_integer_ratio()View examples
Construct from decimal textprice = Decimal('19.95')View examples
Convert an existing float exactlyvalue = Decimal.from_float(binary_value)View examples
Set local precisionwith localcontext() as ctx: ctx.prec = 12View examples
Trap inexact arithmeticctx.traps[Inexact] = TrueView examples
Round to a fixed exponentamount = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)View examples
Multiply then add onceresult = value.fma(multiplier, addend)View examples
Construct an exact fractionratio = Fraction(3, 8)View examples
Parse a decimal fractionratio = Fraction('0.125')View examples
Approximate with a bounded denominatorratio = Fraction(value).limit_denominator(1000)View examples
Calculate an arithmetic meanaverage = statistics.fmean(values)View examples
Calculate a medianmiddle = statistics.median(values)View examples
Calculate sample spreadspread = statistics.stdev(values)View examples
Round with Python's built-in policyrounded = round(value, ndigits)View examples
Format fixed decimal placestext = f'{value:.2f}'View examples

Data and Serialization · 16 commands

Python JSON, CSV, and Data Interchange Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Encode a JSON stringtext = json.dumps(value)View examples
Decode a JSON stringvalue = json.loads(text)View examples
Use interoperable value typespayload = {'ok': True, 'items': [1, 2], 'note': None}View examples
Pretty-print deterministicallytext = json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False)View examples
Emit compact JSONtext = json.dumps(value, separators=(',', ':'), ensure_ascii=False)View examples
Encode to a text streamjson.dump(value, stream)View examples
Decode from a streamvalue = json.load(stream)View examples
Encode a custom typetext = json.dumps(value, default=encode_custom)View examples
Transform decoded objectsvalue = json.loads(text, object_hook=decode_custom)View examples
Parse decimals exactlyvalue = json.loads(text, parse_float=Decimal)View examples
Reject non-finite outputtext = json.dumps(value, allow_nan=False)View examples
Inspect object key pairsvalue = json.loads(text, object_pairs_hook=reject_duplicates)View examples
Read CSV rowsrows = csv.reader(stream, delimiter=',')View examples
Write CSV rowswriter = csv.writer(stream, lineterminator='\n')View examples
Read named CSV fieldsrows = csv.DictReader(stream)View examples
Write named CSV fieldswriter = csv.DictWriter(stream, fieldnames=['name', 'note'])View examples

Data and Serialization · 18 commands

Python pickle, shelve, and Persistent Objects Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Serialize to bytespayload = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)View examples
Load trusted bytesvalue = pickle.loads(payload)View examples
Write a pickle filewith open(path, 'wb') as stream: pickle.dump(value, stream, protocol=5)View examples
Read the newest protocolprotocol = pickle.HIGHEST_PROTOCOLView examples
Target protocol 4payload = pickle.dumps(value, protocol=4)View examples
Read the default protocolprotocol = pickle.DEFAULT_PROTOCOLView examples
Customize serialized statedef __getstate__(self): return {'version': 1, 'value': self.value}View examples
Restore validated statedef __setstate__(self, state): self.value = validate(state)View examples
Define a reductiondef __reduce__(self): return (type(self), (self.value,))View examples
Register a type reducercopyreg.pickle(ValueType, reduce_value)View examples
Use a private reducer tablepickler.dispatch_table = {ValueType: reduce_value}View examples
Emit an external identifierdef persistent_id(self, obj): return ('Record', obj.key)View examples
Resolve an external identifierdef persistent_load(self, pid): return repository.fetch(pid)View examples
Open a shelfwith shelve.open(path, flag='c', writeback=False) as db: use(db)View examples
Persist a mutable updatevalue = db[key]; value.append(item); db[key] = valueView examples
Synchronize a shelfdb.sync()View examples
Disassemble without loadingpython -m pickletools payload.pickleView examples
Override global resolutiondef find_class(self, module, name): raise pickle.UnpicklingError('globals forbidden')View examples

Data and Serialization · 20 commands

Python Random Sampling and Statistics Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a local generatorrng = random.Random(seed)View examples
Capture generator statestate = rng.getstate()View examples
Restore generator staterng.setstate(state)View examples
Draw from range semanticsvalue = rng.randrange(start, stop, step)View examples
Choose one elementitem = rng.choice(population)View examples
Sample without replacementitems = rng.sample(population, k=3)View examples
Sample by relative weightdraws = rng.choices(population, weights=weights, k=100)View examples
Draw a uniform floatvalue = rng.uniform(low, high)View examples
Draw from a normal modelvalue = rng.normalvariate(mu, sigma)View examples
Generate random bytestoken = secrets.token_bytes(32)View examples
Generate a URL-safe tokentoken = secrets.token_urlsafe(32)View examples
Choose securelycharacter = secrets.choice(alphabet)View examples
Compute an arithmetic meancenter = statistics.mean(values)View examples
Compute a mediancenter = statistics.median(values)View examples
Find all most-common valuesmodes = statistics.multimode(values)View examples
Estimate sample spreadspread = statistics.stdev(sample)View examples
Measure population spreadspread = statistics.pstdev(population)View examples
Compute linear correlationcoefficient = statistics.correlation(xs, ys)View examples
Estimate sample quartilescuts = statistics.quantiles(values, n=4, method='exclusive')View examples
Summarize observed endpointscuts = statistics.quantiles(values, n=4, method='inclusive')View examples

Data and Serialization · 13 commands

Python Regular Expressions Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Compile a patternpattern = re.compile(r'\d{4}-\d{2}-\d{2}')View examples
Search anywherematch = pattern.search(text)View examples
Match from startmatch = pattern.match(text)View examples
Validate the whole stringmatch = pattern.fullmatch(text)View examples
Capture a groupvalue = match.group(1)View examples
Named capturer'(?P<year>\d{4})-(?P<month>\d{2})'View examples
Non-capturing groupr'(?:https?|ftp)://'View examples
Iterate matchesfor match in pattern.finditer(text): print(match.span())View examples
Collect matchesvalues = pattern.findall(text)View examples
Split by patternparts = re.split(r'\s*,\s*', text)View examples
Replace matchesclean = re.sub(r'\s+', ' ', text).strip()View examples
Verbose patternpattern = re.compile(r'''...''', re.VERBOSE)View examples
Ignore casepattern = re.compile(r'error', re.IGNORECASE)View examples

Data and Serialization · 17 commands

Python Text Encoding and Unicode Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Encode UTF-8payload = text.encode('utf-8')View examples
Decode UTF-8text = payload.decode('utf-8')View examples
Use strict decodingtext = payload.decode('utf-8', errors='strict')View examples
Open UTF-8 textwith open(path, 'r', encoding='utf-8') as stream: text = stream.read()View examples
Write stable LF newlineswith open(path, 'w', encoding='utf-8', newline='\n') as stream: stream.write(text)View examples
Wrap a binary streamtext_stream = io.TextIOWrapper(binary_stream, encoding='utf-8', newline='')View examples
Normalize canonical compositionnormalized = unicodedata.normalize('NFC', text)View examples
Check normalizationok = unicodedata.is_normalized('NFC', text)View examples
Build a caseless keykey = unicodedata.normalize('NFC', text).casefold()View examples
Lowercase for presentationlowered = text.lower()View examples
Read a code pointnumber = ord(character)View examples
Create a charactercharacter = chr(number)View examples
Read a Unicode namename = unicodedata.name(character, 'UNNAMED')View examples
Replace malformed inputtext = payload.decode('utf-8', errors='replace')View examples
Preserve OS bytestext = payload.decode(filesystem_encoding, errors='surrogateescape')View examples
Create a streaming decoderdecoder = codecs.getincrementaldecoder('utf-8')(errors='strict')View examples
Finish a decode streamtail = decoder.decode(b'', final=True)View examples

Data and Serialization · 20 commands

Python XML Parsing and Generation Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Parse an XML valueroot = ET.fromstring(xml_bytes)View examples
Parse an XML filetree = ET.parse(path)View examples
Catch malformed XMLexcept ET.ParseError as error: report(error.position)View examples
Create an expanded nametag = '{urn:books}title'View examples
Query with a prefix mapitems = root.findall('b:item', {'b': 'urn:books'})View examples
Choose a serialization prefixET.register_namespace('b', 'urn:books')View examples
Find one matching elementitem = root.find('./item[@id="a"]')View examples
Find matching elementsitems = root.findall('.//item')View examples
Iterate matching descendantsfor item in root.iter('item'): consume(item)View examples
Append a child elementchild = ET.SubElement(parent, 'item', {'id': item_id})View examples
Set element textchild.text = valueView examples
Remove a childparent.remove(child)View examples
Serialize to textxml_text = ET.tostring(root, encoding='unicode')View examples
Write UTF-8 XMLtree.write(path, encoding='utf-8', xml_declaration=True)View examples
Canonicalize XMLcanonical = ET.canonicalize(xml_data=xml_text)View examples
Iterate completed elementsevents = ET.iterparse(source, events=('end',))View examples
Release processed contentelement.clear()View examples
Create a pull parserparser = ET.XMLPullParser(events=('start', 'end'))View examples
Inspect the Expat versionversion = pyexpat.EXPAT_VERSIONView examples
Bound XML input bytesif len(xml_bytes) > MAX_XML_BYTES: raise ValueError('XML too large')View examples
CMDMEMO TERMINALREAD ONLY