The snippet library.
Small, practical examples. Search by task or narrow things down below.
Escape text for HTML content
Python: Use html.escape before placing plain text in an HTML text or quoted attribute context.
Python✓ Tested
Explain a calculation with a comment
Python: Keep the code executable while documenting why a fixed input is used.
Python✓ Tested
Extract filename components
Python: Use pathlib properties to separate a directory, filename stem, and suffix.
Python✓ Tested
Extract named regex fields
Python: Use named capture groups to parse a known date-shaped identifier.
Python✓ Tested
Extract numbers from text
Find all runs of ASCII digits in a string and convert the matches to integers.
regex✓ Tested
Filter a list with a condition
Build a new list containing only the values that satisfy a condition using a list comprehension.
list✓ Tested
Find common factors and multiples
Python: Use the integer gcd and lcm helpers to avoid floating-point calculations.
Python✓ Tested
Find matching files recursively
Python: Use rglob and sorted relative paths for a reproducible recursive file listing.
Python✓ Tested
Find the first matching value with a fallback
Python: Pass a generator and default to next to avoid building an intermediate list.
Python✓ Tested
Find the mean and median of readings
Python: Use statistics helpers to distinguish an arithmetic mean from a middle value.
Python✓ Tested
Find the number of days in a month
Python: Use calendar.monthrange to account for leap years.
Python✓ Tested
Find values missing from another collection
Python: Use a set difference to identify requested IDs absent from the available IDs.
Python✓ Tested