Medium: Interview Core · Problem 27 of 82

Make a Slug

MediumStringsPython

A slug is the readable part of a web address, such as my-first-post. Write slugify(title) that:

  • turns the title into lower case,
  • keeps only the letters a to z and digits 0 to 9,
  • joins the words with single hyphens, replacing any run of other characters with one hyphen,
  • has no hyphen at the start or at the end.

The tests use only English letters, digits, spaces and punctuation.

Understand the problem

Apply the rules by hand.

What is slugify("Hello, World!")?

Lower case gives hello, world!. The comma and the space together are one run of other characters, so they become one hyphen. The trailing ! would make a hyphen at the end, which is removed.

What is slugify(" Python 3.12 -- What's New? ")?

The words are python, 3, 12, what, s, new. The dot, the dashes and the apostrophe are all "other characters" and split words. Every run of them becomes one hyphen, and the spaces at both ends leave no hyphens.

Write the solution

Return the slug. An empty result is fine for a title with no letters or digits.

def slugify(title):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

If you could cut the title into words made only of letters and digits, what would be left to do?

Hint 2: the shape of the answer

Walk through the lower-case title. Collect letters and digits into the current word; any other character ends the current word. At the end, join the words with "-". (Or use re.sub on [^a-z0-9]+.)

Reflect

Solution: by hand

def slugify(title):
    words = []
    current = []
    for ch in title.lower():
        if "a" <= ch <= "z" or "0" <= ch <= "9":
            current.append(ch)
        elif current:
            words.append("".join(current))
            current = []
    if current:
        words.append("".join(current))
    return "-".join(words)

Another way: a regular expression

import re

def slugify(title):
    return re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")

What this tests: string iteration, building words, join, and (in the second version) re.sub and strip.

The traps: several non-letters in a row should give one hyphen ("a -- b"), and the title may start or end with punctuation. The regular expression handles the first with the + (one or more) and the second with strip("-").

Why not str.replace(" ", "-")? It only handles spaces, so punctuation stays and double spaces give double hyphens.

Cost: O(n).

What an interviewer might ask next: Real slugs must handle accents ("Café" becomes "cafe"). How would you? (unicodedata.normalize("NFKD", ...) and drop the accent marks.)