String helpers
- Python course
- Intermediate
- Lesson 14/116
- 6 min
Add string processing methods.
The slugify method
We'll write a slugify method to turn a string into a URL-friendly form. The method lowercases the letters and replaces spaces with hyphens; this makes titles or tags fit for links.
Example: "Hello World".lower().replace(" ", "-") gives "hello-world". We'll add this as a slugify(self, text) method on the class. The method takes a parameter and returns the transformed string. The same shape works for titles, tags and file names.
Method chaining
Chaining is passing the result of one method to another with a dot. text.lower().replace(...) first calls lower(), then sends its result to replace().
Read left to right: text → .lower() → lowercased string → .replace(...) → hyphenated string. Each step returns a str, so the chain continues. This style is short and readable.
Practice Add slugify to Utility
Add a def slugify(self, text): method to the Utility class. In the body write return text.lower().replace(" ", "-"). Then create an instance with u = Utility() and call print(u.slugify("Hello World")).
Starter code
class Utility:
version = "1.0"
print(Utility.version)
# Add the slugify method and call it on an instanceSample solution
class Utility:
version = "1.0"
def slugify(self, text):
return text.lower().replace(" ", "-")
u = Utility()
print(u.slugify("Hello World"))Expected output
hello-world
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does slugify("Hello World") return?
- HelloWorld
- hello-world Correct answer
- hello_world
- HELLO WORLD
Explanation: lower() lowercases, replace(" ", "-") turns spaces into hyphens.
2 Complete the slugify body
class Utility:
def slugify(self, text):
return text.____().replace(" ", "-")
class Utility:
def slugify(self, text):
return text.lower().replace(" ", "-")
Explanation: lower() lowercases the letters; chaining continues with replace.
3 Match the slugify parts
| Term | Meaning |
|---|---|
slugify |
Method name |
text.lower() |
Lowercase |
.replace(" ", "-") |
Space to hyphen |