Turn Unicode Titles into URL Slugs

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

PythonData Integrity

Code

pythonsnippet
34 lines
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()

How it works

The callable surface is the functions slugify and main — everything else is wiring.

The loop for source, expected in cases.items() is the only repeated construct. The import line is the dependency contract: annotations comes from __future__ and nothing else.

What to watch for

  • __future__ and unicodedata must be installed first — the snippet imports them directly.

Applying it

The one signature that matters here is def slugify(text: str, *, max_length: int = 60) -> str

The demo output is labeled (slug ->), so every line in the printed output names the step that produced it.

There are 1 call inside main — slugify — executed top to bottom.

Statements that matter

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",
}

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `__future__` and `unicodedata` must be present in the project or the import fails at load time.