Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
