Converts a string to a URL-friendly slug.
- Use
str.lower()
andstr.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'