snippetpythonTip
Convert a Python string to a slug
Viewed 0 times
pythonstringslugconvert
Problem
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
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.Solution
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'Code Snippets
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'Context
From 30-seconds-of-code: slugify
Revisions (0)
No revisions yet.