How to Slugify a String in Python
Convert any text into a URL-friendly slug using the standard library's unicodedata and re modules.
Python code
13 linesimport re
import unicodedata
def slugify(text):
text = unicodedata.normalize('NFKD', text)
text = text.encode('ascii', 'ignore').decode('ascii')
text = re.sub(r'[^\w\s-]', '', text).strip().lower()
text = re.sub(r'[-\s]+', '-', text)
return text
if __name__ == "__main__":
title = "Hello, World! This is a Test — Slugify Me"
print(slugify(title))
Output
hello-world-this-is-a-test-slugify-me
How it works
The function normalizes Unicode characters to their decomposed form and removes accents, making the string ASCII-safe. It then strips non-word characters and whitespace, lowers the case, and replaces spaces and dashes with a single hyphen. This produces clean, readable slugs suitable for URLs or file names.
Common mistakes
- Forgetting to handle Unicode characters like accented letters or em dashes
- Not trimming whitespace before replacing spaces, leading to leading/trailing hyphens
- Using `-` replacement on empty strings, which can produce double hyphens if not collapsed
Variations
- Use a third-party library like `python-slugify` for more control over transliteration.
- Append a random suffix or a numeric ID to ensure uniqueness in a database.
Real-world use cases
- Generating SEO-friendly URLs for blog posts from their titles.
- Creating consistent file names for downloaded resources based on content names.
- Producing safe identifiers for caching keys when normalizing user-generated content.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.