python 29 lines · 7 steps

Building URL-safe slugs in Python

Turn arbitrary titles into clean, collision-free URL slugs using Unicode normalization, regex, and a suffix counter.

Explained by highlit
1import re
2import unicodedata
3 
4_SLUG_STRIP = re.compile(r"[^\w\s-]")
5_SLUG_HYPHENATE = re.compile(r"[-\s]+")
6 
7 
8def slugify(title, max_length=80, separator="-"):
9 normalized = unicodedata.normalize("NFKD", title)
10 ascii_only = normalized.encode("ascii", "ignore").decode("ascii")
11 
12 cleaned = _SLUG_STRIP.sub("", ascii_only).strip().lower()
13 slug = _SLUG_HYPHENATE.sub(separator, cleaned)
14 
15 if len(slug) > max_length:
16 slug = slug[:max_length].rsplit(separator, 1)[0]
17 
18 return slug.strip(separator)
19 
20 
21def unique_slug(title, existing):
22 base = slugify(title) or "untitled"
23 if base not in existing:
24 return base
25 
26 suffix = 2
27 while f"{base}-{suffix}" in existing:
28 suffix += 1
29 return f"{base}-{suffix}"
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Unicode NFKD normalization plus ASCII encoding strips accents down to plain letters safely.
  2. 2Precompiling regexes at module load avoids recompiling them on every call.
  3. 3Appending an incrementing numeric suffix is a simple way to guarantee uniqueness against an existing set.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building URL-safe slugs in Python — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code