w3resource

Python: Replace whitespaces with an underscore and vice versa


23. Swap Spaces and Underscores

Write a Python program to replace whitespaces with an underscore and vice versa.

Sample Solution:

Python Code:

import re
text = 'Python Exercises'
text =text.replace (" ", "_")
print(text)
text =text.replace ("_", " ")
print(text)

Sample Output:

Python_Exercises                                                                                              
Python Exercises

Pictorial Presentation:

Python: Regular Expression - Replace whitespaces with an underscore and vice versa.
Python: Regular Expression - Replace whitespaces with an underscore and vice versa.

Flowchart:

Flowchart: Regular Expression - Replace whitespaces with an underscore and vice versa.

For more Practice: Solve these Related Problems:

  • Write a Python program to replace all spaces in a string with underscores and then convert underscores back to spaces.
  • Write a Python script to perform a bidirectional swap between spaces and underscores in a given string.
  • Write a Python program to toggle all spaces to underscores in a string and then reverse the process.
  • Write a Python program to search for both spaces and underscores in a string and swap them using regex substitution.

Go to:


Previous: Write a Python program to find the occurrence and position of the substrings within a string.
Next: Write a Python program to extract year, month and date from a an url.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.