Removeprefix Removesuffix Trim Known Affixes
str.removeprefix and str.removesuffix strip a known affix and return the string untouched when it is absent, replacing fragile slicing.
Page 4 of 6
str.removeprefix and str.removesuffix strip a known affix and return the string untouched when it is absent, replacing fragile slicing.
shlex.split applies POSIX shell quoting rules to a command string, so quoted spaces, literal hashes and escapes arrive as one argv list ready for subprocess.
Stage a release directory with shutil: copy2 preserves metadata, move relocates the source away, copytree clones whole trees, disk_usage reports bytes.
splitlines recognizes every Unicode line boundary — CRLF, NEL, and line separators included — while a plain split on newline leaves carriage returns behind.
ljust and rjust pad strings to a fixed width for aligned report columns, while zfill zero-fills numeric codes so 7 becomes 000007.
str.partition cuts at the first separator, rpartition at the last, and a missing separator returns the whole string with two empty halves instead of raising.
Build a codepoint translation table for smart quotes and dashes, compose with NFC normalization first, and delete whole character classes on the fly.
Use string.capwords when str.title breaks words at apostrophes and hyphens: whitespace is the split unit, so contractions render correctly.
traceback.format_exc captures the full interpreter traceback inside except blocks, format_exception_only keeps just the error line, idle calls stay safe.
TypedDict records which config keys are required versus optional, and __required_keys__ plus __optional_keys__ let runtime code inspect that contract.
Use SimpleNamespace for lightweight attribute records: fields read as attributes, vars() exposes the same dict, and equality compares field values.
Describe dict payloads at the type level with TypedDict: required keys stay mandatory, NotRequired keys are consumed behind membership checks.
unicodedata.normalize with NFD splits accented letters into base plus combining marks; dropping category Mn code points turns Zoë into Zoe for search keys.
WeakValueDictionary holds values weakly: entries disappear when the last strong reference dies, while live entries keep normal dict semantics like get.
zip(*rows) unpacks a list of rows so every column becomes one tuple: transpose tables, align headers with values, then zip(*columns) reverses it.
Store datetimes in UTC and convert with ZoneInfo: one meeting renders as different wall clocks, and New York moves between UTC-5 and UTC-4 with DST.
Combine tallies with Counter algebra: plus merges totals, minus cancels and drops non-positive counts, and intersection and union take mins and maxes.
Group records without missing-key guards: nested defaultdict(int) totals build buckets on first touch, and a list factory collects failures in arrival order.
Use dict.keys() and dict.items() views as sets: subtract to find added and removed keys, intersect for changed pairs, and rely on views tracking live mutations.
Compare expected versus actual text with difflib: unified_diff prints review-style diffs, SequenceMatcher scores similarity, get_close_matches suggests keys.
Compose permission sets with IntFlag: bitwise OR grants, the in operator tests a single bit, and iterating a member lists the individual flags it contains.
Build aligned CLI tables with f-string format specs: left and right alignment, fixed precision, fill and center, thousands grouping, and percent rendering.
Keep ratios exact with Fraction: binary floats fail 0.1 plus 0.2 checks, fractions add and scale without drift, and results auto-reduce to lowest terms.
Sort records on several fields at once with itemgetter: dept then salary ordering, one reverse flag for the whole tuple, and attrgetter for dataclass fields.
Walk adjacent pairs with itertools.pairwise: compute deltas between consecutive prices, flag threshold jumps, and close rings by re-appending the first item.
Pass a function to re.sub so every match decides its own replacement: redact secrets with shape preserved, normalize codes, and bump versions in a single pass.
Derive deterministic identifiers with uuid5: hashing a namespace UUID with a natural key yields the same ID everywhere, so re-runs and upserts stay idempotent.
Make uneven inputs loud with zip(strict=True): what plain zip silently truncates becomes an explicit ValueError, even when a streamed side runs dry.
Maintain sorted lists with bisect: insort places items in order, bisect_left and bisect_right answer range questions, and key compares by projection.
Layer defaults, environment values, and CLI flags with collections.ChainMap: earlier mappings win, writes land in the first layer, and defaults stay intact.
Clean up dynamic resource sets with contextlib.ExitStack: enter_context registers handles, callback registers plain functions, and unwinding runs LIFO.
Track recent events with a bounded deque: maxlen evicts the oldest end automatically, both ends are O(1), and rotate shifts the whole window in place.
Parse config strings into enum members with StrEnum, whose members are real strings, and fall back to plain Enum when members carry separate payloads.
Format mixed report values with functools.singledispatch: one str fallback plus registered int, Decimal, date, and list branches replace isinstance chains.
Gate client addresses with the ipaddress module: parse and reject malformed hosts, then test CIDR allowlist membership instead of string prefix compares.
Group equal neighbors into runs with itertools.groupby: adjacency decides grouping, so sort by key for full groups and detect state changes in one pass.
Summarize samples with statistics: quantiles for quartiles and p90, fmean for a one-pass average, stdev for sample spread, all stdlib with no dependencies.
Clean pasted text with str.maketrans and str.translate: map curly quotes, delete control characters, and remap code points in one pass per table.
Render notification copy with string.Template: substitute fails loudly on missing variables, safe_substitute keeps unknown tokens, ${name} disambiguates.
Format terminal text with textwrap: dedent triple-quoted blocks, fill or wrap at a fixed width, and shorten long summaries with an ellipsis placeholder.
Tally hashable items with collections.Counter — most_common ranking, arithmetic merging, and negative-count filtering in one pass.
Run IO-bound tasks on a thread pool, collect results as they finish, and cancel or report stragglers when the global timeout fires.
Wrap acquire and release in a contextmanager generator so exceptions still trigger cleanup and timing or locking boilerplate disappears.
Enforce cross-field invariants in __post_init__ with frozen dataclasses so invalid domain objects raise at construction, not deep in business logic.
Memoize pure functions with lru_cache and cache, inspect hit statistics, and cap memory with maxsize for unbounded argument spaces.
Chunk any iterable lazily with itertools.batched so large datasets stream through fixed-size batches without materializing full lists.
Round-trip data through json dumps and loads with sort_keys and parse hooks so key ordering and numeric types stay contract-stable.
Query directory trees with pathlib glob and rglob, resolve sizes and suffixes, and bucket files by type without os.path string surgery.
Turn unstructured log lines into typed dicts with named capture groups and one compiled pattern, rejecting malformed lines explicitly.
Define a typing.Protocol so any object with the right shape plugs in without inheritance, and verify conformance with runtime isinstance.
Use contextvars for request-scoped correlation IDs in async code without parameter passing.
Run coroutines with a semaphore-limited gather for bounded concurrency in async data fetching pipelines.
Compose async generators into a pipeline for lazy streaming with backpressure.
Propagate cancellation through async tasks with cleanup for graceful shutdown.
Build an event-driven state machine with asyncio for protocol parsing and workflow orchestration.
Run a pool of workers consuming from an asyncio Queue for producer-consumer patterns.
Throttle API calls with asyncio.Semaphore for bounded concurrency in web scraping.
Protect critical sections from cancellation with asyncio.shield for atomic operations.
Use asyncio.TaskGroup with timeout for structured concurrency and automatic cancellation on failure.
Wait for the first of multiple tasks to complete with asyncio.wait for competitive fetching.
Detect negative cycles in weighted graphs using Bellman-Ford for arbitrage detection.
Implement binary search with lower and upper bound variants for sorted array queries.
Implement a bloom filter using hashlib for probabilistic membership testing with false positive control.
Estimate confidence intervals using bootstrap resampling for robust statistical inference.
Configure Celery tasks with retry backoff jitter and max attempts for resilient async jobs.
Validate nested dictionaries with Cerberus schemas for flexible form input validation.
Build a CLI tool with Click subcommands options and help for consistent command interfaces.
Build a consistent hash ring with virtual nodes for distributed cache routing.
Parse Content-Disposition headers for safe filename extraction with RFC 5987 support.
Implement a context manager for deterministic resource cleanup with exception safety.
Measure function execution time with a context manager and decorator for performance profiling.
Implement cursor-based pagination with SQLAlchemy for stable large dataset traversal.
Use Dask for parallel aggregation across partitions with lazy evaluation for large datasets.
Define a dataclass with Pydantic for runtime validation type coercion and JSON serialization.
Apply retry with exponential backoff via a decorator for resilient function calls.
Recursively merge nested dictionaries with conflict resolution for config composition.
Generate deterministic test fixtures with factory_boy for reproducible test data.
Handle file uploads in Django with size limit type validation and virus scan scheduling.
Implement JWT authentication with access and refresh tokens in Django REST Framework.
Use TypeVar and Generic for type-safe container classes with static type checking.
Find the leftmost position where a sorted list can accept a target using bisect-style binary search lower bound.
Generate a Gray code sequence of n bits using bit manipulation where consecutive values differ by one bit.
Implement a bloom filter with k hash functions for probabilistic membership testing in Python.
Implement a binary search tree supporting insert and delete using in-order successor for two-child nodes.
Compute single source shortest paths in a weighted graph using Dijkstra with heapq for efficient extraction.
Compute the Levenshtein edit distance between two strings with insert, delete, and substitute operations.
Find the shortest path in an unweighted graph using BFS with a predecessor dict for path reconstruction.
Perform topological sort on a DAG using DFS with cycle detection via tri-color marking.
Implement a hash table with open addressing and double hashing for collision resolution in Python.
Sort a list by building a max heap in place then repeatedly extracting the maximum to the end.
Match a pattern in text using KMP with a precomputed failure function for linear time matching.
Solve the 0-1 knapsack problem using dynamic programming with a one dimensional rolling array.
Compute the longest common subsequence of two strings using dynamic programming with full table reconstruction.
Count inversions in a list using a modified mergesort that counts crossings during the merge step.
Generate all primes up to n using a segmented sieve of Eratosthenes for memory efficiency on large ranges.
Sort a list in place using quicksort with median-of-three pivot selection to avoid worst-case on sorted input.
Find all occurrences of a pattern in text using Rabin Karp with a rolling hash for O(n+m) average time.
Implement a skip list supporting insert, delete, and search with probabilistic level assignment in Python.
Build a trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.
Implement a disjoint set union find with path compression and union by rank for near constant amortized time.