Python: Replace Spaces with Hyphens for Slug
Transform a string by stripping surrounding whitespace and replacing each space with a hyphen to create a simple slug.
Python code
7 linesdef slugify(text):
return text.strip().replace(" ", "-")
if __name__ == "__main__":
title = "Hello World Python Example"
result = slugify(title)
print(result)
Output
Hello-World-Python-Example
How it works
The function first calls strip() to remove any leading or trailing whitespace, ensuring no stray hyphens appear at the edges. Then replace(" ", "-") globally switches every literal space character in the string to a hyphen. Because replace returns a new string, the original text stays untouched — strings in Python are immutable. This is a minimal slugifier that works only for spaces and does not handle punctuation, case folding, or non-ASCII characters.
Common mistakes
- Forgetting to call strip() first, which can leave leading or trailing hyphens
- Assuming replace() changes the string in place — it returns a new string
- Using replace() on multiple consecutive spaces produces multiple hyphens instead of one
- Not accounting for tabs or newlines, which remain unchanged
Variations
- Use a regex like re.sub(r'\s+', '-', text.strip()) to collapse any whitespace into one hyphen
- Chain .lower() to make the slug all lowercase for typical URL use
Real-world use cases
- Generating URL-friendly slugs from blog post titles before storing in a database.
- Creating file names from user input where spaces would cause issues in file paths.
- Normalizing category or tag names in an e-commerce system for consistent links.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.