Skip to content
GreenSnippets

Slugify a string

Turn text into a lowercase, hyphenated, ASCII-only slug using only the standard library.

Python
import re
import unicodedata


def slugify(text, max_length=80):
    text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
    text = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
    return text[:max_length].rstrip("-")

Example / expected output

Output
slugify("Crème Brûlée: the 5-minute recipe!")  # 'creme-brulee-the-5-minute-recipe'

How it works

unicodedata.normalize("NFKD", ...) separates accents from letters, and encoding to ASCII with ignore drops them. Remaining non-alphanumeric runs become one hyphen. Characters with no ASCII equivalent (for example Chinese) are removed, so use a transliteration library if you need those.