Knowee
Questions
Features
Study Tools

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

Question

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

🧐 Not the exact question you are looking for?Go ask a question

Solution

Here’s a Python program that replaces whitespaces with an underscore and vice versa:

def replace_whitespaces(string):
    # Replace spaces with underscores and underscores with spaces
    new_string = ''
    for char in string:
        if char == ' ':
            new_string += '_'
        elif char == '_':
            new_string += ' '
        else:
            new_string += char
    return new_string

# Example usage
input_string = "Hello World_this is a_test"
result = replace_whitespaces(input_string)
print(result)  # Output: Hello_World this is a test

Explanation

  • The function replace_whitespaces iterates through each character in the input string.
  • It checks if the character is a space; if so, it replaces it with an underscore.
  • If the character is an underscore, it replaces it with a space.
  • Other characters remain unchanged.
  • Finally, the modified string is returned.

This problem has been solved

Similar Questions

Which method can be used to remove any whitespace from both the beginning and the end of a string?

What will be the output of below Python code?str1="Aplication"str2=str1.replace('a','A')print(str2)applicationApplicationApplicAtionapplicAtion

Write a program to replace all spaces from text with - (dash)from the file podar.txt.

What kind of error is caused by improper spacing at the beginning of a line in Python code?

Python program that accepts a string and calculate the number of digits and letters and space

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.