slugme.ioclean-url-slug-generator

How to Slugify a String in Python (3 Ways, Tested)

Turn any string into a URL slug in Python with python-slugify, Django's slugify or a dependency-free function, with tested output and the Unicode traps to avoid.

By 5 min read
How to Slugify a String in Python (3 Ways, Tested)

Python gives you at least three reasonable ways to turn "Straße & Café: Don't Miss!" into a URL slug, and they produce three different answers. This guide covers each one, shows real output (every example below was run on Python 3.9 with python-slugify 8.0.4 and Django 4.2), and explains which to choose.

Just need a slug, not code? Paste your title into the URL slug generator — or convert a whole list with the bulk slug generator.

python-slugify is the de facto standard. It transliterates Unicode to ASCII (using text-unidecode by default), so almost any input produces a sensible slug.

pip install python-slugify
from slugify import slugify

slugify('Hello World!')        # 'hello-world'
slugify('Straße & Café')       # 'strasse-cafe'
slugify('Łódź Guide')          # 'lodz-guide'
slugify('Привет мир')          # 'privet-mir'
slugify('影師嗎')               # 'ying-shi-ma'

Note the package name is python-slugify but the import is slugify. There is a different, unrelated package on PyPI called slugify; if both are installed, imports collide. When in doubt, pip show python-slugify.

Useful options

# Custom separator
slugify('Hello World', separator='_')                         # 'hello_world'

# Max length, cut at a word boundary
slugify('A very long title about slugs and urls', max_length=20)                      # 'a-very-long-title-ab'
slugify('A very long title about slugs and urls', max_length=20, word_boundary=True)  # 'a-very-long-title'

# Stop words
slugify('The Quick Brown Fox', stopwords=['the'])             # 'quick-brown-fox'

# Custom replacements, applied before transliteration
slugify('10 Tips & Tricks', replacements=[['&', 'and']])      # '10-tips-and-tricks'
slugify("Don't Stop", replacements=[["'", '']])               # 'dont-stop'

# German-style umlauts
slugify('Straße in München',
        replacements=[['ü', 'ue'], ['ö', 'oe'], ['ä', 'ae']])  # 'strasse-in-muenchen'

Two defaults are worth overriding in most projects:

  • Apostrophes split words. Without a replacement, slugify("Don't Stop") returns don-t-stop.
  • Umlauts lose their dots (Größe → grosse). For German content, add the ae/oe/ue replacements above.

Option 2: Django's built-in slugify

If you are in a Django project, django.utils.text.slugify is already available:

from django.utils.text import slugify

slugify('Hello World!')     # 'hello-world'
slugify("Don't Stop")       # 'dont-stop'

It is simple and fast, but understand what it does. With the default allow_unicode=False, Django normalizes the text to NFKD and throws away every non-ASCII character — it does not transliterate. That works for accents (é decomposes to e + accent), but not for letters that don't decompose, or for other scripts:

slugify('Straße & Café')    # 'strae-cafe'   ← the ß is gone
slugify('Łódź Guide')       # 'odz-guide'    ← the Ł is gone
slugify('Привет мир')       # ''             ← empty!
slugify('影師嗎')            # ''             ← empty!

An empty slug is a real production bug: it produces URLs like /blog/ or violates a unique constraint the second time it happens. You have two fixes:

# Keep native scripts (pair with SlugField(allow_unicode=True))
slugify('Привет мир', allow_unicode=True)   # 'привет-мир'

# Or transliterate with python-slugify inside Django
from slugify import slugify as transliterate_slugify
transliterate_slugify('Straße')             # 'strasse'

Generating the slug on save

The usual Django pattern is to fill a SlugField from the title the first time the object is saved — and never again, so editing a title doesn't silently change a published URL:

from django.db import models
from slugify import slugify


class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=80, unique=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            base = slugify(self.title, max_length=70, word_boundary=True) or 'post'
            slug, n = base, 2
            while Post.objects.filter(slug=slug).exclude(pk=self.pk).exists():
                slug = f'{base}-{n}'
                n += 1
            self.slug = slug
        super().save(*args, **kwargs)

The or 'post' fallback guarantees a slug even for an all-emoji title. The loop resolves collisions with -2, -3 suffixes — see how to handle duplicate slugs for why the unique constraint must stay in place even with this check.

Option 3: a dependency-free slugify function

If you can't add a dependency, the standard library gets you most of the way. The trick is unicodedata.normalize('NFKD') plus an explicit table for the letters NFKD can't decompose:

import re
import unicodedata

SPECIALS = str.maketrans({
    'ß': 'ss', 'æ': 'ae', 'œ': 'oe', 'ø': 'o', 'ł': 'l',
    'đ': 'd', 'ð': 'd', 'þ': 'th', 'ı': 'i',
})


def slugify(text: str, separator: str = '-', max_length: int = 0) -> str:
    text = text.replace('&', ' and ')
    text = re.sub(r"['’]", '', text)              # don't -> dont
    text = text.lower().translate(SPECIALS)      # ß, ø, ł… before NFKD drops them
    text = unicodedata.normalize('NFKD', text)
    text = text.encode('ascii', 'ignore').decode('ascii')
    words = re.findall(r'[a-z0-9]+', text)
    slug = separator.join(words)
    if max_length and len(slug) > max_length:
        cut = slug[:max_length + 1]
        # Back up to the last whole word; hard-cut a single over-long word.
        slug = cut.rsplit(separator, 1)[0] if separator in cut else slug[:max_length]
    return slug
slugify('Straße & Café')                     # 'strasse-and-cafe'
slugify("Don't Stop Me Now")                 # 'dont-stop-me-now'
slugify('  Łódź — Guide (2026)!  ')          # 'lodz-guide-2026'
slugify('The Quick Brown Fox Jumps', max_length=15)  # 'the-quick-brown'
slugify('Hello World', separator='_')        # 'hello_world'

How it works, line by line:

  1. & → and keeps the meaning of "Rock & Roll" instead of deleting it.
  2. Apostrophes are removed, not replaced, so contractions stay one word.
  3. The SPECIALS table runs before normalization. NFKD can't decompose ß or ł, so the encode('ascii', 'ignore') step would delete them.
  4. NFKD + ASCII encode strips accents: é → e, ñ → n.
  5. re.findall(r'[a-z0-9]+') extracts words, which automatically removes punctuation and collapses repeated separators.
  6. Max length backs up to the last full word.

This function returns an empty string for Cyrillic, Arabic or Chinese, just like Django. If your content includes those scripts, use python-slugify — writing transliteration tables for every script is not a good use of your time.

Which option should you choose?

Situation Use
Any project with user-written or multilingual titles python-slugify
Django project, titles guaranteed ASCII/European accents Django slugify
Django project, want native-script URLs Django slugify(..., allow_unicode=True)
No dependencies allowed, Latin-script content The DIY function above

For a side-by-side comparison with JavaScript, PHP and Ruby libraries on the same inputs, see slugify libraries compared.

Before you ship: check the output

Whichever option you pick, run your real titles through it and look at the result. The URL slug checker flags slugs that are too long, contain stop words or special characters, or would read badly in search results — and the generator shows what a clean slug for the same title looks like.

Frequently asked questions

What is the difference between python-slugify and slugify on PyPI?

They are different packages that both install a module called slugify. python-slugify (by un33k) is the maintained, widely used one. Installing both causes import conflicts, so if `from slugify import slugify` behaves strangely, run `pip show python-slugify slugify` and uninstall the one you don't want.

How do I keep Unicode characters in a Django slug?

Use `slugify(value, allow_unicode=True)` and a SlugField with `allow_unicode=True`. The result keeps native scripts, e.g. "привет-мир" or "أفضل-نصائح-السيو".

How do I limit slug length in Python?

python-slugify supports `slugify(text, max_length=60, word_boundary=True)`, which trims at a word boundary instead of cutting a word in half. Django's SlugField has max_length=50 by default, so pass a larger value if your slugs are longer.

Keep reading