Complete Python Series · Part 15 of 29
Assignment 02-slug-generator
NextGen CTO — Python Assignments
A collection of practical Python exercises based on real-world scenarios from the NextGen CTO learning platform. Each assignment includes starter code, hints, a complete solution, and an explanation.
Exercise: NextGen CTO Course URL Slug Generator
Learn to clean and transform strings using Python's strip(), lower(), split(), and join() methods to generate consistent course URL slugs.
Problem statement
When an instructor creates a course on NextGen CTO, the course title may contain uppercase letters, leading or trailing whitespace, and multiple spaces between words. The platform needs to generate a clean, readable URL slug from the title. For example, Python Programming Basics should become python-programming-basics.
Task requirements
- Capture the raw course title using
input(). - Remove leading and trailing whitespace.
- Convert the title to lowercase.
- Split the title into words, handling repeated whitespace.
- Join the words using hyphens (
-). - Print the resulting course URL slug.
Constraints
- Use built-in Python string methods only.
- Do not use
ifstatements, loops, or regular expressions. - Assume the title contains only letters, numbers, and whitespace, with at least one word.
Good luck trying the exercise!
Starter code
# TODO: Get the raw course title from the user
# TODO: Clean the title and split it into words
# Hint: You can chain string methods
# TODO: Join the words using hyphens
# TODO: Print the final course URL slug
Expected output
Enter course title: Python Programming Basics
Course URL slug: python-programming-basics
Hints
- Use
strip()to remove leading and trailing whitespace. - Use
lower()to convert characters to lowercase. - Use
split()without an argument to handle multiple consecutive whitespace characters. - Use
"-".join(words)to combine words with hyphens.
Solution: NextGen CTO Course URL Slug Generator
The solution chains string methods to normalize the course title and uses join() to create a readable, hyphen-separated URL slug.
# Get the raw course title
raw_title = input("Enter course title: ")
# Clean the title and split it into words
words = raw_title.strip().lower().split()
# Generate the URL slug
slug = "-".join(words)
# Display the final slug
print(f"Course URL slug: {slug}")
Solution explanation
- Line 2:
input()captures the course title as a string. - Line 5:
strip()removes surrounding whitespace,lower()converts the title to lowercase, andsplit()creates a list of words while ignoring repeated whitespace. - Line 8:
"-".join(words)combines the words with a hyphen between each pair, producing a URL slug. - Line 11: An f-string displays the generated slug.
For example, Advanced Python Course becomes advanced-python-course. Unlike split(" "), split() does not create empty strings for repeated spaces. Joining with hyphens rather than spaces produces the intended slug.