Files
30-seconds-of-code/snippets/slugify.md
Isabelle Viktoria Maciohsek 19f636408c Make expertise a field
2022-03-01 20:27:27 +02:00

587 B

title, tags, expertise, firstSeen, lastUpdated
title tags expertise firstSeen lastUpdated
String to slug string,regexp intermediate 2020-10-05T21:57:34+03:00 2020-10-25T12:43:20+02:00

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'