pysnippets.strings.slugify
Turn text into a URL slug
slugify(text: str) -> str
Make a lowercase, ASCII, hyphen-separated slug from any text, including accented letters.
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)- 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).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
- NFKD normalisation splits each accented letter into a base letter plus an accent mark.
- Encoding to ASCII with
ignoredrops the marks, and any other non-ASCII character. re.findallpicks out runs of letters and digits;'-'.joinglues them together. Leading and trailing separators can’t happen.
Complexity: O(n) time, O(n) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from 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.