- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Replace the Spaces of a String with a Specific Character
In Python, the spaces of a string with a special character can be replaced using replace() method. The replace method replaces all occurrences of the passed substring with a new substring. In this article, we will see how we can use replace() method to replace the spaces of a string with another specific substring.
Syntax of Replace Method
The syntax of the replace method is as follows −
string.replace(old, new[, count])
The replace method takes two inputs, one is the old string which is the substring you want to replace and another input is the new string which is the substring that you want at the place of the old substring, and a count to specify how many occurrences of the old string you want to replace. If the count is not provided it replaces all occurrences of the old string with the new string.
Example: Replace Spaces with Hyphens
To replace the spaces of the string with a hyphen we need to pass the old string as a space (‘ ’) and the new string as a hyphen (‘-’) to the replace() method. In the below example, we have replaced all the spaces of the string with hyphens.
s = "Hello World" s = s.replace(' ', '-') print(s)
Example 2: Replace Spaces with Underscore
To replace the spaces of the string with an underscore we need to pass the old string as space (‘ ’) and the new string as underscore (‘_’) in the replace method. The code for the same is as follows −
s = "This is a sentence." s = s.replace(' ', '_') print(s)
Example 3: Replace Only a Limited Number of Spaces
To replace a limited number of spaces we need to use the count input as well when calling the replace method. In the below example, we will replace only the first two spaces of the string with an underscore so we pass the count value as 2. The code for replacing a limited number of spaces with special characters is as follows −
s = "I am learning Python programming." s = s.replace(' ', '_', 2) print(s)
I_am_learning Python programming.
In this article, we understood how we can use replace() method to replace the spaces in the string with a special character. The replace method takes the old string to be replaced, the new string to be replaced with and the count of the number of replacements to be performed as input and returns the replaced string as output.
Kickstart Your Career
Get certified by completing the courseGet Started