Python Program to Replace Blank Space with Hyphen in a String

Write a Python program to Replace Blank Space with Hyphen in a String using replace function, and For Loop with a practical example.

Python Program to Replace Blank Space with Hyphen in a String Example 1

This python program allows the user to enter a string. Next, we used built-in replace string function to replace empty space with a hyphen.

# Python program to Replace Blank Space with Hyphen in a String
 
str1 = input("Please Enter your Own String : ")

str2 = str1.replace(' ', '_')

print("Original String :  ", str1)
print("Modified String :  ", str2)

Python replace blank spaces in a string with Hyphen output

Please Enter your Own String : Hello World Program
Original String :   Hello World Program
Modified String :   Hello_World_Program

Python Program to Replace Spaces with Hyphen in a String Example 2

In this program program, we used For Loop to iterate each character in a String. Inside the For Loop, we are using the If Statement to check whether the String character is empty or blank space. If true, Python will replace it with _.

# Python program to Replace Blank Space with Hyphen in a String
 
str1 = input("Please Enter your Own String : ")

str2 = ''

for i in range(len(str1)):
    if(str1[i] == ' '):
        str2 = str2 + '_'
    else:
        str2 = str2 + str1[i]
        
print("Modified String :  ", str2)

Python replace blank spaces in a string with Hyphen output

Please Enter your Own String : Hello World!
Modified String :   Hello_World!
>>> 
Please Enter your Own String : Python program Output
Modified String :   Python_program_Output

Python Program to Replace Empty Space with Hyphen in a String Example 3

This Python replace space with hyphen program is the same as the above example. However, we are using For Loop with Object.

# Python program to Replace Blank Space with Hyphen in a String
 
str1 = input("Please Enter your Own String : ")

str2 = ''

for i in str1:
    if(i == ' '):
        str2 = str2 + '_'
    else:
        str2 = str2 + i
        
print("Modified String :  ", str2)
Python program to Replace Blank Space with Hyphen in a String 3