Skip to content

Instantly share code, notes, and snippets.

@devster31
Last active September 12, 2022 12:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devster31/cf1258925df16c093f6177c0c62167e8 to your computer and use it in GitHub Desktop.
Save devster31/cf1258925df16c093f6177c0c62167e8 to your computer and use it in GitHub Desktop.
[Slugify] #python
import re
import unicodedata
def slugify(value, allow_unicode=False):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
underscores, or hyphens. Convert to lowercase. Also strip leading and
trailing whitespace, dashes, and underscores.
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize('NFKC', value)
else:
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value.lower())
return re.sub(r'[-\s]+', '-', value).strip('-_')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment