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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Unicode NFKD normalization plus ASCII encoding strips accents down to plain letters safely.
- 2Precompiling regexes at module load avoids recompiling them on every call.
- 3Appending an incrementing numeric suffix is a simple way to guarantee uniqueness against an existing set.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-url-safe-slugs-in-python-explained-python-d236/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.