Turn Unicode Titles into URL Slugs
Turn Unicode headings into stable ASCII URL slugs with transliteration, separator collapsing, and length limits.
Code
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__andunicodedatamust 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
URL Slug GeneratorCreate readable URL slugs from titles and phrases with accent removal, configurable separators, and a maximum length while preserving Unicode letters.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.