How to Slugify a String in Python

Convert any text into a URL-friendly slug using the standard library's unicodedata and re modules.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

13 lines
Python 3.9+
import 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

stdout
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

  1. Use a third-party library like `python-slugify` for more control over transliteration.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.