fluttersmith/py-snippetsGitHub ↗

Turn text into a URL slug

Make a lowercase, ASCII, hyphen-separated slug from any text, including accented letters.

Strings#text#conversionO(n) time✓ 3 examples pass on 3.11–3.14

Crème brûlée should become creme-brulee, not crme-brle and not crème-brûlée.

slugify.py✓ ruff · mypy --strict
import re
import unicodedata


def slugify(text: str) -> str:
    """Turn ``text`` into a lowercase, URL-safe slug."""
    ascii_text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
    words = re.findall(r"[a-z0-9]+", ascii_text.lower())
    return "-".join(words)
  1. splits "é" into "e" + accent, then drops anything non-ASCII
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> slugify("Hello World!")'hello-world'passed on Python 3.11 to 3.14: >>> slugify("  Crème brûlée -- 2nd_edition ")'creme-brulee-2nd-edition'passed on Python 3.11 to 3.14: >>> slugify("!!!")''
Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).

How it works

  • NFKD normalisation splits each accented letter into a base letter plus an accent mark.
  • Encoding to ASCII with ignore drops the marks, and any other non-ASCII character.
  • re.findall picks out runs of letters and digits; '-'.join glues them together. Leading and trailing separators can’t happen.

Complexity: O(n) time, O(n) space

Importfrom pysnippets.strings.slugify import slugifyNo dependencies: copy slugify.py into your project, or clone the repo.

Adapted from slugify in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Rewritten: transliterates accents to ASCII, simpler regex; typed. Suggest an edit.