Python Program to Take in a String and Replace Every Blank Space with Hyphen

When it is required to take a string and replace every blank space with a hyphen, the ‘replace’ method can be used. It takes two parameters, the blank space, and the value with which it needs to be replaced (hyphen in this case).

Below is a demonstration of the same −


 Live Demo

my_string = input("Enter a string :")
print("The string entered by user is :")
my_string = my_string.replace(' ','-')
print("The modified string:")


Enter a string : A-B-C-D E-
A-B-C-D E-
The string entered by user is :
A-B-C-D E-
The modified string:


  • An input string is asked to be entered by the user.

  • It is done with the help of the ‘input’ method.

  • The string entered by the user is displayed on the console.

  • The ‘replace’ method is used to replace an empty space with a hyphen.

  • The changed string is then displayed on the console.