Last active
May 23, 2020 16:20
-
-
Save gary-liguoliang/ba951765b5b00388f5b25398239668f4 to your computer and use it in GitHub Desktop.
slugify strings with pure regex and python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
def slugify(s: str) -> str: | |
s_after_basic_replacement = re.sub("[^a-zA-Z0-9]", "-", s) | |
s_with_no_continues_dash = re.sub("[-]+", "-", s_after_basic_replacement) | |
s_with_no_ending_dash = re.sub("-$", "", s_with_no_continues_dash) | |
return s_with_no_ending_dash | |
if __name__ == '__main__': | |
print(slugify("is this a good title? ")) | |
# is-this-a-good-title | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment