Added slugify (#286)

Co-authored-by: Isabelle Viktoria Maciohsek <maciv@hotmail.gr>
This commit is contained in:
Jay Patel
2020-10-06 00:27:34 +05:30
committed by GitHub
parent 5a639e263b
commit 336b5b78a8

24
snippets/slugify.md Normal file
View File

@ -0,0 +1,24 @@
---
title: slugify
tags: string,regex,intermediate
---
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.
```py
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
```
```py
slugify('Hello World!') # 'hello-world'
```