138

I am in search of the best way to "slugify" string what "slug" is, and my current solution is based on this recipe

I have changed it a little bit to:

s = 'String to slugify'

slug = unicodedata.normalize('NFKD', s)
slug = slug.encode('ascii', 'ignore').lower()
slug = re.sub(r'[^a-z0-9]+', '-', slug).strip('-')
slug = re.sub(r'[-]+', '-', slug)

Anyone see any problems with this code? It is working fine, but maybe I am missing something or you know a better way?

7
  • 1
    are you working with unicode alot? if so, the last re.sub might be better if you wrap unicode() around it, This is what django does. Also, the [^a-z0-9]+ can be shortened to use \w . see django.template.defaultfilters, it's close to yours, but a bit more refined. Apr 7, 2011 at 0:23
  • Are unicode characters allowed in URL? Also, I have changed \w to a-z0-9 because \w includes _ character and uppercase letters. Letters are set to lowercase in advance, so there will be no uppercase letters to match.
    – Zygimantas
    Apr 7, 2011 at 1:21
  • '_' is valid (but your choice, you did ask), unicode is as percent encoded chars. Apr 7, 2011 at 1:36
  • Thank you Mike. Well, I asked a wrong question. Is there any reason to encode it back to unicode string, if we already replaced all characters except "a-z", "0-9" and "-" ?
    – Zygimantas
    Apr 7, 2011 at 1:47
  • For django, I believe it's important to them to have it all strings as unicode objects for compatibility. It's your choice if you want this. Apr 7, 2011 at 1:51

12 Answers 12

206

There is a python package named python-slugify, which does a pretty good job of slugifying:

pip install python-slugify

Works like this:

from slugify import slugify

txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")

txt = 'Nín hǎo. Wǒ shì zhōng guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")

txt = 'Компьютер'
r = slugify(txt)
self.assertEquals(r, "kompiuter")

txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a")

See More examples

This package does a bit more than what you posted (take a look at the source, it's just one file). The project is still active (got updated 2 days before I originally answered, over nine years later (last checked 2022-03-30), it still gets updated).

careful: There is a second package around, named slugify. If you have both of them, you might get a problem, as they have the same name for import. The one just named slugify didn't do all I quick-checked: "Ich heiße" became "ich-heie" (should be "ich-heisse"), so be sure to pick the right one, when using pip or easy_install.

5
  • 7
    python-slugify is licensed under MIT, but it uses Unidecode which is licensed under GPL, so it might not fit for some projects.
    – Rotareti
    Aug 6, 2017 at 21:40
  • @Rotareti Could you please explain for me why it is could not fit all the projects? Can't we use anything under MIT or GPL license and include them inside commercial software? I think the only restriction is putting the license besides the codes we develop. Am I wrong? Jul 14, 2019 at 22:18
  • 1
    @GhassemTofighi In short: You can use it in your commercial software, but if you use it, you must open source your code as well. Anyway IANAL and this is no legal advice.
    – Rotareti
    Jul 15, 2019 at 8:04
  • @GhassemTofighi maybe take a look at softwareengineering.stackexchange.com/q/47032/71504 on that topic
    – kratenko
    Jul 17, 2019 at 9:11
  • 4
    @Rotareti python-slugify now defaults to the Artistic License'd text-unidecode instead of the GPL-licensed Unidecode, addressing your licensing concern. github.com/un33k/python-slugify/commit/…
    – Emilien
    Jul 27, 2019 at 23:49
41

Install unidecode form from here for unicode support

pip install unidecode

# -*- coding: utf-8 -*-
import re
import unidecode

def slugify(text):
    text = unidecode.unidecode(text).lower()
    return re.sub(r'[\W_]+', '-', text)

text = u"My custom хелло ворлд"
print slugify(text)

>>> my-custom-khello-vorld

7
  • 1
    hi, its a bit strange but it give for my res like that "my-custom-ndud-d-d3-4-d2d3-4nd-d-"
    – derevo
    Jul 30, 2012 at 7:04
  • 1
    @derevo that happend when you don't send unicode strings. Replace slugify("My custom хелло ворлд") with slugify(u"My custom хелло ворлд"), and it should work.
    – kratenko
    Dec 16, 2012 at 12:10
  • 11
    I would suggest against using variable names like str. This hides the builtin str type.
    – crodjer
    Apr 19, 2014 at 7:22
  • 2
    unidecode is GPL, which may not be suitable for some. Apr 25, 2015 at 6:59
  • What about the reslugifying or deslugifying.
    – Ryan Chou
    Jan 24, 2019 at 3:46
12

There is python package named awesome-slugify:

pip install awesome-slugify

Works like this:

from slugify import slugify

slugify('one kožušček')  # one-kozuscek

awesome-slugify github page

2
  • 4
    Nice package! But be careful, it's licensed under GPL.
    – Rotareti
    Aug 6, 2017 at 21:27
  • 1
    Heads up: this won't automatically .lower() your urls. You'll need to run slugify(text).lower() if you want that. Apr 6, 2019 at 17:38
9
def slugify(value):
    """
    Converts to lowercase, removes non-word characters (alphanumerics and
    underscores) and converts spaces to hyphens. Also strips leading and
    trailing whitespace.
    """
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
    value = re.sub('[^\w\s-]', '', value).strip().lower()
    return mark_safe(re.sub('[-\s]+', '-', value))
slugify = allow_lazy(slugify, six.text_type)

This is the slugify function present in django.utils.text This should suffice your requirement.

8

It works well in Django, so I don't see why it wouldn't be a good general purpose slugify function.

Are you having any problems with it?

2
  • The code has moved to here.
    – raylu
    Jul 21, 2016 at 4:43
  • 24
    For the lazies: from django.utils.text import slugify
    – Spartacus
    Dec 6, 2017 at 23:29
8

The problem is with the ascii normalization line:

slug = unicodedata.normalize('NFKD', s)

It is called unicode normalization which does not decompose lots of characters to ascii. For example, it would strip non-ascii characters from the following strings:

Mørdag -> mrdag
Æther -> ther

A better way to do it is to use the unidecode module that tries to transliterate strings to ascii. So if you replace the above line with:

import unidecode
slug = unidecode.unidecode(s)

You get better results for the above strings and for many Greek and Russian characters too:

Mørdag -> mordag
Æther -> aether
4

Unidecode is good; however, be careful: unidecode is GPL. If this license doesn't fit then use this one

3

A couple of options on GitHub:

  1. https://github.com/dimka665/awesome-slugify
  2. https://github.com/un33k/python-slugify
  3. https://github.com/mozilla/unicode-slugify

Each supports slightly different parameters for its API, so you'll need to look through to figure out what you prefer.

In particular, pay attention to the different options they provide for dealing with non-ASCII characters. Pydanny wrote a very helpful blog post illustrating some of the unicode handling differences in these slugify'ing libraries: http://www.pydanny.com/awesome-slugify-human-readable-url-slugs-from-any-string.html This blog post is slightly outdated because Mozilla's unicode-slugify is no longer Django-specific.

Also note that currently awesome-slugify is GPLv3, though there's an open issue where the author says they'd prefer to release as MIT/BSD, just not sure of the legality: https://github.com/dimka665/awesome-slugify/issues/24

1

You might consider changing the last line to

slug=re.sub(r'--+',r'-',slug)

since the pattern [-]+ is no different than -+, and you don't really care about matching just one hyphen, only two or more.

But, of course, this is quite minor.

1

Another option is boltons.strutils.slugify. Boltons has quite a few other useful functions as well, and is distributed under a BSD license.

1

another nice answer for creating it could be this form

import re
re.sub(r'\W+', '-', st).strip('-').lower()
0

By your example, a fast manner to do that could be:

s = 'String to slugify'

slug = s.replace(" ", "-").lower()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.