Skip to content
This repository was archived by the owner on May 7, 2023. It is now read-only.

Files

Latest commit

 

History

History
27 lines (22 loc) · 564 Bytes

slugify.md

File metadata and controls

27 lines (22 loc) · 564 Bytes
title type tags cover dateModified
String to slug
snippet
string
regexp
sliced-fruits
2020-10-25 12:43:20 +0200

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'