Slugify a title in Python
How titles become URL slugs.
import re
def slugify(title):
slug = title.lower().strip()
slug = re.sub(r"[^a-z0-9]+", "-", slug)
return slug.strip("-")
How it works
- Lowercases and trims the title.
re.subcollapses runs of non-alphanumerics into single hyphens.- Stray hyphens at the ends are stripped.
Keywords and builtins used here
defreturnslugify
The run, in numbers
- Lines
- 6
- Characters to type
- 122
- Tokens
- 45
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 28 seconds.
Step 7 of 9 in Strings, step 13 of 72 in Language basics.