Text

Contents

Text#

String-bashing snippets. Each block is the canonical short form.

Strip and lowercase in one call.

key = raw.strip().lower()

Split on the first occurrence and bind both halves.

head, _, tail = line.partition("=")

Split into a fixed-width left column and the rest.

prefix, rest = s[:8], s[8:]

Join a list of fragments with a separator.

csv_line = ",".join(map(str, row))

Replace many substrings via a translation table.

safe = s.translate(str.maketrans({"<": "&lt;", ">": "&gt;", "&": "&amp;"}))

Pad an integer to a fixed width with leading zeros.

stamp = f"{n:08d}"

Format a float to fixed decimals.

price = f"{x:.2f}"

Truncate or pad to a fixed display width.

col = f"{name:<20.20}"

Extract an IPv4 from any line of text.

import re
IPV4 = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
ips = IPV4.findall(line)

Match-and-bind with the walrus.

if (m := re.match(r"^(?P<user>\w+)@(?P<host>[\w.-]+)$", target)):
    user, host = m["user"], m["host"]

Substitute via regex.

redacted = re.sub(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", "X.X.X.X", line)

Detect and strip a known suffix (3.9+).

stem = name.removesuffix(".log")

Pull every line that matches a pattern from a stream.

errs = [line for line in stream if "ERROR" in line]

References#

  • Snippets for the snippets catalogue.

  • str for the full str surface.

  • Regex for the regex DSL.