Python Program to Take in a String and Replace Every Blank Space with Hyphen

When it is required to take a string and replace every blank space with a hyphen, the replace() method can be used. It takes two parameters: the blank space, and the value with which it needs to be replaced (hyphen in this case).

Below is a demonstration of the same −

Using replace() Method

text = "Hello world Python programming"
print("Original string:")
print(text)

modified_text = text.replace(' ', '-')
print("Modified string:")
print(modified_text)
Original string:
Hello world Python programming
Modified string:
Hello-world-Python-programming

Interactive Example

Here's an example that takes user input ?

my_string = input("Enter a string: ")
print("The string entered by user is:")
print(my_string)

my_string = my_string.replace(' ', '-')
print("The modified string:")
print(my_string)

Multiple Methods Comparison

Using split() and join()

text = "Python is awesome"
print("Original:", text)

# Split by spaces and join with hyphens
result = '-'.join(text.split(' '))
print("Modified:", result)
Original: Python is awesome
Modified: Python-is-awesome

Using Regular Expressions

import re

text = "Learn Python programming"
print("Original:", text)

# Replace spaces with hyphens using regex
result = re.sub(r' ', '-', text)
print("Modified:", result)
Original: Learn Python programming
Modified: Learn-Python-programming

Comparison

Method Simplicity Performance Best For
replace() High Fast Simple replacements
split() + join() Medium Fast Multiple spaces
Regular expressions Low Slower Complex patterns

Conclusion

The replace() method is the simplest and most efficient way to replace spaces with hyphens. Use split() and join() for handling multiple consecutive spaces, and regular expressions for complex pattern matching.

Updated on: 2026-03-25T18:34:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements