IC Improve Code Recipes

Recipe 15.6 · Python

String Helpers: Truncate, Slugify, Mask

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Three small string jobs come up in almost every business app. Text must be cut to fit a column or a grid cell. Titles must become URL-friendly slugs. Account numbers and e-mail addresses must be masked in logs, screens and e-mails. The homegrown versions break on short input, accented characters and emoji, or reveal more than they hide.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Truncate, URL-slug and card-mask helpers that crash, mangle and leak (p341_r15_6_truncate_slug_mask_before.py)
"""Truncate, URL-slug and card-mask helpers that crash, mangle and leak

Source: ImproveCode, Chapter 15, Recipe 15.6 "String Helpers: Truncate, Slugify, Mask"
Section: The way it's often written
Book page: 341-342  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Python slicing never throws, so a _substring helper reproduces String.Substring's
ArgumentOutOfRangeException to keep the original crash behaviour.
"""

# Not to copy: crashes, mangles and leaks.


def _substring(s: str, start: int, length: int | None = None) -> str:
    end = len(s) if length is None else start + length
    if start < 0 or start > len(s) or end > len(s):
        raise IndexError("Index and length must refer to a location within the string.")
    return s[start:end]


def truncate(s: str, length: int) -> str:
    return _substring(s, 0, length) + "..."  # crashes if shorter


def make_url(title: str) -> str:
    return title.lower().replace(" ", "-").replace("&", "").replace("'", "")  # "Crème" stays


def mask_card(card: str) -> str:
    return "XXXX-XXXX-XXXX-" + _substring(card, 12)

The improved recipe

Usage snippet:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Safe Truncate, Slugify, Mask and MaskEmail text helpers (p342_r15_6_text_helpers_truncate_slugify_mask.py)
"""Safe Truncate, Slugify, Mask and MaskEmail text helpers

Source: ImproveCode, Chapter 15, Recipe 15.6 "String Helpers: Truncate, Slugify, Mask"
Section: The improved recipe
Book page: 342-344  -- original C# listing
Converted from C# to Python.
string.Normalize(FormD) and UnicodeCategory become unicodedata.normalize("NFD") and
unicodedata.category() == "Mn". Python strings index by code point, so the C# surrogate
check in _cut is unnecessary and kept only as a plain slice.
"""

import unicodedata


def truncate(value: str | None, max_length: int, ellipsis: str = "...") -> str:
    if max_length < 0:
        raise ValueError("max_length must not be negative.")
    if not value or len(value) <= max_length:
        return value or ""

    if max_length <= len(ellipsis):
        return _cut(value, max_length)

    return _cut(value, max_length - len(ellipsis)).rstrip() + ellipsis


def slugify(text: str | None, max_length: int = 80) -> str:
    if text is None or not text.strip():
        return ""

    decomposed = unicodedata.normalize("NFD", text)
    slug: list[str] = []
    pending_dash = False

    for c in decomposed:
        if unicodedata.category(c) == "Mn":
            continue

        if not (c.isascii() and c.isalnum()):
            pending_dash = len(slug) > 0
            continue

        needed = 2 if pending_dash else 1
        if len(slug) + needed > max_length:
            break

        if pending_dash:
            slug.append("-")
            pending_dash = False

        slug.append(c.lower())

    return "".join(slug)


def mask(value: str | None, visible_at_end: int = 4, mask_char: str = "*") -> str:
    if not value:
        return ""

    # Never reveal more than half of the value.
    visible = max(0, min(visible_at_end, len(value) // 2))
    return mask_char * (len(value) - visible) + value[len(value) - visible:]


def mask_email(email: str | None) -> str:
    if email is None or not email.strip():
        return ""

    at = email.find("@")
    if at <= 0:
        return mask(email, 0)

    return email[0] + "***" + email[at:]


def _cut(value: str, length: int) -> str:
    # Python str indexes code points, so no surrogate pair can be split here.
    return value[:length]

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Example inputs and outputs for the truncate, slugify and mask helpers (p344_r15_6_text_helpers_examples.py)
"""Example inputs and outputs for the truncate, slugify and mask helpers

Source: ImproveCode, Chapter 15, Recipe 15.6 "String Helpers: Truncate, Slugify, Mask"
Section: The improved recipe
Book page: 344  -- original C# listing
Converted from C# to Python.
The expected results from the C# comments are kept as comments next to each call.
"""

from p342_r15_6_text_helpers_truncate_slugify_mask import mask, mask_email, slugify, truncate


def examples() -> None:
    truncate("Quarterly compliance report", 15)
    # "Quarterly co..."
    slugify("Crème Brûlée & Co.: 2026 Menu!")
    # "creme-brulee-co-2026-menu"
    mask("4111111111111111")  # "************1111"
    mask_email("pat.lee@example.com")  # "p***@example.com"

How it works

Truncate returns short input unchanged, never returns null, and counts the ellipsis inside the limit, so a 50-character column really gets at most 50 characters. Cut steps back one position if the cut would split a surrogate pair, which otherwise leaves half a character that turns into a replacement character once the text is encoded as UTF-8.

Slugify decomposes the text with Unicode normalization form D, which splits é into e plus a combining accent, and then drops the accents. Only ASCII letters and digits survive; every run of anything else becomes a single dash, and leading and trailing dashes never appear. The length limit is checked before each append, so the slug never ends in a dash after being cut.

Mask shows at most the last few characters and never more than half of the value, so a short value is not fully exposed by a default meant for card numbers. MaskEmail shows the first character and the domain and always uses three stars, so the mask doesn't reveal the length of the name.

Variations and pitfalls

  • Some letters don't decompose: ß, æ, ø and ł are dropped by Slugify. If your content uses them, add a small replacement table (ß to ss, æ to ae) before the loop.
  • Slugs for non-Latin titles come out empty. Fall back to the record ID, and store the slug once rather than recomputing it, so links don't break when a title is edited.
  • Truncate counts UTF-16 code units. For text with emoji or combining marks shown to users, cut on text elements with StringInfo instead. For database columns, code units are what nvarchar(n) counts, so the simple version is correct.
  • Masking is for display. Logs should not receive the full value at all, masked afterwards or not. See Chapter 4.
  • Slugify builds its result in a StringBuilder, not with += in the loop. About 16,471 files in the archive append to a string with += "...", in 33 engagements. Inside a loop that copies the whole string on every pass; for a handful of pieces it doesn't matter, for a few thousand rows it does.