Python Program to Replace Blank Spaces with Hyphens

This article deals with one of the very simple program in Python, that is a program that replaces all blank spaces from given string with hyphens. Here are the list of programs covered in this article:

Replace Blank Spaces from String with Hyphens

The question is, write a Python program to replace blank spaces available in a given string with hyphens. The answer to this question is the program given below:

print("Enter the String: ")
str = input()

newstr = ""
for i in range(len(str)):
    if str[i] == ' ':
        newstr = newstr + '_'
    else:
        newstr = newstr + str[i]

print("\nNew String is:", newstr)

Here is its sample run. The snapshot given below is the initial output:

python replace blank spaces with hyphens

Now supply the input say Welcome to fresherearth as string and press ENTER key to replace all the available spaces with hyphens like shown in the sample output given below:

replace blank spaces with hyphens python

Replace Blank Spaces with Hyphens using replace()

Now this program uses replace(), a pre-defined method of Python that takes mainly two arguments. The first argument's value gets replaced by the second argument's value. You can also provide the third argument as the number of times to replace the thing. But here, we only require two arguments to replace all blank spaces with hyphens.

print("Enter the String: ", end="")
str = input()

str = str.replace(' ', '_')
print("\nBlank spaces replaced with hyphens successfully!")
print("\nThe new string =", str)

Here is its sample run with user input, This is a Python program.:

python program replace blank space with hyphen

Python Online Test


« Previous Program Next Program »