Slugify a string
Turn text into a lowercase, hyphenated, ASCII-only slug using only the standard library.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
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
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.
Related snippets
- PHP Tested
Slugify a string in PHP
Create URL-safe lowercase slugs from titles, removing accents and punctuation.
- JavaScript Tested
Slugify a string for URLs
Convert any title into a lowercase, hyphenated, accent-free slug that is safe to use in a URL.
- HTML
Essential head tags for SEO and sharing
The meta, canonical, Open Graph and icon tags every public page should have.
- JavaScript Tested
Truncate a string with an ellipsis
Shorten text to a maximum length without cutting in the middle of a word or a Unicode character.

