Turn Unicode Titles into URL Slugs

Turn Unicode headings into stable ASCII URL slugs with transliteration, separator collapsing, and length limits.

PythonData Integrity

Code

snippet
from __future__ import annotations

import re
import unicodedata


def slugify(text: str, *, max_length: int = 60) -> str:
    normalized = unicodedata.normalize("NFKD", text)
    ascii_text = normalized.encode("ascii", "ignore").decode("ascii")
    ascii_text = ascii_text.lower()
    ascii_text = re.sub(r"[^a-z0-9]+", "-", ascii_text).strip("-")
    if len(ascii_text) > max_length:
        ascii_text = ascii_text[:max_length].rsplit("-", 1)[0].strip("-")
    return ascii_text or "untitled"


def main() -> None:
    cases = {
        "Hello, World!": "hello-world",
        "  Café au lait  ": "cafe-au-lait",
        "Über alles": "uber-alles",
        "Python 3.13 — New Features": "python-3-13-new-features",
        "你好世界": "untitled",
    }
    for source, expected in cases.items():
        result = slugify(source)
        print(f"slug -> {result}")
        assert result == expected
    assert len(slugify("word " * 30, max_length=20)) <= 20


if __name__ == "__main__":
    main()