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
Python Program to Replace the Spaces of a String with a Specific Character
In Python, spaces in a string can be replaced with specific characters using the replace() method. The replace() method substitutes all occurrences of a specified substring with a new substring. This article demonstrates how to use replace() to replace spaces with various characters.
Syntax
The syntax of the replace() method is ?
string.replace(old, new[, count])
Parameters
- old The substring to be replaced
- new The replacement substring
- count (optional) Number of occurrences to replace. If omitted, all occurrences are replaced
Example 1: Replace Spaces with Hyphens
To replace spaces with hyphens, pass a space ' ' as the old string and a hyphen '-' as the new string ?
text = "Hello World Python"
result = text.replace(' ', '-')
print("Original:", text)
print("Modified:", result)
The output of the above code is ?
Original: Hello World Python Modified: Hello-World-Python
Example 2: Replace Spaces with Underscore
Similarly, spaces can be replaced with underscores by passing '_' as the replacement character ?
sentence = "This is a Python tutorial"
modified_sentence = sentence.replace(' ', '_')
print("Original:", sentence)
print("Modified:", modified_sentence)
The output of the above code is ?
Original: This is a Python tutorial Modified: This_is_a_Python_tutorial
Example 3: Replace Limited Number of Spaces
Use the count parameter to replace only a specific number of spaces. This example replaces only the first two spaces ?
text = "I am learning Python programming language"
result = text.replace(' ', '_', 2)
print("Original:", text)
print("Modified:", result)
The output of the above code is ?
Original: I am learning Python programming language Modified: I_am_learning Python programming language
Example 4: Replace Spaces with Special Characters
Spaces can be replaced with any character, including special symbols ?
text = "Python Data Science"
result1 = text.replace(' ', '*')
result2 = text.replace(' ', '@')
result3 = text.replace(' ', '|')
print("With asterisk:", result1)
print("With at symbol:", result2)
print("With pipe:", result3)
The output of the above code is ?
With asterisk: Python*Data*Science With at symbol: Python@Data@Science With pipe: Python|Data|Science
Comparison of Methods
| Method | Use Case | Example |
|---|---|---|
replace(' ', '-') |
All spaces to hyphens | "Hello World" ? "Hello-World" |
replace(' ', '_', 1) |
First space only | "Hello World Python" ? "Hello_World Python" |
replace(' ', '*') |
All spaces to special chars | "Hello World" ? "Hello*World" |
Conclusion
The replace() method provides a simple way to substitute spaces with any character. Use the optional count parameter to limit replacements when needed.
