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.
TIP: Please refer String article to understand everything about Python Strings.
# 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)
OUTPUT
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 character is empty or blank space. If true, repack 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)
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)
OUTPUT