Home › Learn › Python › Strings in depth

String methods

Lesson 26 of 40. Split, join, strip, replace, and search text.

Strings cannot be changed, so every method returns a new string. The ones you will use daily: .split() breaks text into a list of words (or on a separator you pass), "-".join(parts) glues a list back together, .strip() removes whitespace from both ends, .replace(old, new) swaps text, .startswith() and .endswith() ask about the edges, .find(sub) gives the index of a substring or -1, and in asks whether it is there at all. .strip() also takes an argument: .strip(".,!") removes those characters from both ends instead of whitespace.

Chaining is normal: title.strip().lower().replace(" ", "-"). Each step returns a string and the next method runs on that.

line = "  name: Ada  "
key, value = line.strip().split(": ")
print(key, value)             # name Ada
print("-".join(["a", "b"]))   # a-b

Your task

Write slugify(title) that turns a title into a URL slug: lower case, surrounding whitespace removed, spaces replaced with hyphens, and every character that is not a letter, digit, or hyphen dropped. " Hello World! " becomes "hello-world".

Then write clean_words(text) returning the words of text in lower case with the characters in PUNCTUATION stripped from both ends of each word, and any word that becomes empty dropped. "The cat, the hat!" gives ["the", "cat", "the", "hat"].

Part of the final project. clean_words turns raw text into the list of lower-case words everything else counts. It is saved in this browser and loaded into Project: text statistics when you get there.

Hint 1

text = title.strip().lower().replace(" ", "-"), then build the result one character at a time: keep c if c.isalnum() or c == "-".

Hint 2

for raw in text.lower().split(): word = raw.strip(PUNCTUATION); if word: result.append(word)

Show the solution
PUNCTUATION = ".,!?;:"


def slugify(title):
    text = title.strip().lower().replace(" ", "-")
    result = ""
    for c in text:
        if c.isalnum() or c == "-":
            result += c
    return result


def clean_words(text):
    result = []
    for raw in text.lower().split():
        word = raw.strip(PUNCTUATION)
        if word:
            result.append(word)
    return result

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.