Split and Join

Split and Join

split cuts a string into a list. Without arguments it cuts on whitespace:

sentence = "the quick brown fox"
words = sentence.split()
print(words)

Output:

['the', 'quick', 'brown', 'fox']

With an argument it cuts on that separator:

print("2026-07-15".split("-"))

Output:

['2026', '07', '15']

join is the reverse: it glues a list of strings together with a separator. The separator is the string the method is called on:

words = ["the", "quick", "brown", "fox"]
print(" ".join(words))
print("-".join(words))

Output:

the quick brown fox
the-quick-brown-fox

Exercise

A slug is a lowercase, hyphen-separated form of a title, used in web addresses.

  1. Define a function named to_slug with one parameter, title.
  2. It returns the slug: lowercased, words joined by -.

to_slug("My First Post") returns "my-first-post".

Run your code to see the output, then press Submit.

Tests

import unittest


class TestToSlug(unittest.TestCase):
    def test_three_words(self):
        self.assertEqual(to_slug("My First Post"), "my-first-post")

    def test_one_word(self):
        self.assertEqual(to_slug("Hello"), "hello")

    def test_extra_spaces_do_not_produce_extra_hyphens(self):
        self.assertEqual(to_slug("  spaced   out  "), "spaced-out")
def to_slug(title):
    return "-".join(title.lower().split())


print(to_slug("My First Post"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.