typestar

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

  1. Lowercases and trims the title.
  2. re.sub collapses runs of non-alphanumerics into single hyphens.
  3. Stray hyphens at the ends are stripped.

Keywords and builtins used here

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.

Type this snippet

Step 7 of 9 in Strings, step 13 of 72 in Language basics.

← Previous Next →