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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 13 views 0 copies

Python code

7 lines
Python 3.9+
def slugify(text):
    return text.strip().replace(" ", "-")

if __name__ == "__main__":
    title = "Hello World Python Example"
    result = slugify(title)
    print(result)

Output

stdout
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

  1. Use a regex like re.sub(r'\s+', '-', text.strip()) to collapse any whitespace into one hyphen
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.