Convert a Python string to a slug - 30 seconds of code Skip to content

Home

Convert a Python string to a slug

A slug is a URL-friendly version of a string, typically used in URLs to identify a resource. Slugs use only lowercase letters, numbers, and hyphens, and are often used to generate human-readable URLs.

In order to convert any string to a slug, you first need to use str.lower() and str.strip() to normalize the input string. Then, you can use re.sub() and regular expressions to replace spaces, dashes, and underscores with hyphens, and remove any special characters.

from re import sub

def slugify(s):
  s = s.lower().strip()
  s = re.sub(r'[^\w\s-]', '', s)
  s = re.sub(r'[\s_-]+', '-', s)
  s = re.sub(r'^-+|-+$', '', s)
  return s

slugify('Hello World!') # 'hello-world'

More like this

  • Collection · 11 articles

    Python Strings

    Learn how to format and manipulate strings in Python 3.6 with this article collection.

  • Python ·

    Convert between hex and RGB

    Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components and vice versa.

Start typing a keyphrase to see matching articles.