String to slug

Python, String, Regexp · Oct 25, 2020

Converts a string to a URL-friendly slug.

  • Use str.lower() and str.strip() to normalize the input string.
  • Use re.sub() to to replace spaces, dashes and underscores with - and remove special characters.
import re

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

  • String to words

    Converts a given string into a list of words.

    Python, String · Nov 2, 2020

  • Hex to RGB

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

    Python, String · Sep 15, 2020

  • RGB to hex

    Converts the values of RGB components to a hexadecimal color code.

    Python, String · Nov 2, 2020