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 flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 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.