URL Slugs from Any Text

easy
Unit 2 · Strings II0/3 to milestone

Turn titles into URL-safe slugs: "Crème Brûlée & Café!" → "creme-brulee-cafe".

Implement slugify(text, max_len=None):

  1. Normalise with unicodedata.normalize("NFKD", text) and drop non-ASCII characters (this strips accents).
  2. Lowercase, and replace every run of characters other than a-z0-9 with a single -. Strip leading and trailing -.
  3. If max_len is set and the slug is longer, cut it to max_len characters. If that cut a word in half (the next character isn't -) and the cut slug contains a -, drop the partial word. Strip trailing -.

Then implement unique_slug(text, existing): the slug, or slug-2, slug-3, … (the first one not in the set existing).

#strings#unicode#web2 visible + 1 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
URL Slugs from Any Text · TechGradify