w3resource

Python: Expand Spaces


Replace Spaces with Underscore and Hyphen

Write a Python program to find a string such that, when three or more spaces are compacted to a '-' and one or two spaces are replaced by underscores, leads to the target.

Input: 
Python-Exercises
Output:
Python   Exercises

Input:  
Python_Exercises
Output:
Python Exercises

Input:  
-Hello,_world!__This_is-so-easy!-
Output:
Hello, world!  This is   so   easy! 

Visual Presentation:

Python: Expand Spaces .

Sample Solution:

Python Code:

# License: https://bit.ly/3oLErEI

# Function to replace hyphens with three spaces and underscores with a single space
def test(strs):
    return strs.replace("-", " " * 3).replace("_", " ")

# Test cases with different strings
strs = "Python-Exercises"
print("Original strings:", strs)
print("Depth of groups of matched nested parentheses separated by parentheses:")
print(test(strs))

strs = "Python_Exercises"
print("\nOriginal strings:", strs)
print("Depth of groups of matched nested parentheses separated by parentheses:")
print(test(strs))

strs = "-Hello,_world!__This_is-so-easy!-"
print("\nOriginal strings:", strs)
print("Depth of groups of matched nested parentheses separated by parentheses:")
print(test(strs))

Sample Output:

Original strings: Python-Exercises
Depth of groups of matched nested parentheses separated by parentheses:
Python   Exercises

Original strings: Python_Exercises
Depth of groups of matched nested parentheses separated by parentheses:
Python Exercises

Original strings: -Hello,_world!__This_is-so-easy!-
Depth of groups of matched nested parentheses separated by parentheses:
   Hello, world!  This is   so   easy!  

Flowchart:

Flowchart: Python - Expand Spaces .

For more Practice: Solve these Related Problems:

  • Write a Python program to replace sequences of three or more spaces with a hyphen and one or two spaces with an underscore.
  • Write a Python program to use regular expressions to compact multiple spaces into a '-' if three or more, or '_' if one or two.
  • Write a Python program to iterate through a string and substitute spaces according to the number of consecutive spaces detected.
  • Write a Python program to implement a function that replaces long space sequences with '-' and short ones with '_' in an input string.

Python Code Editor :

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

Previous: Compute the depth of groups of matched nested parentheses separated by parentheses.
Next: Find four positive even integers whose sum is n.

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.