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 −

Example

 Live Demo

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

Output

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:
A-B-C-D--E-

Explanation

  • 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.

Updated on: 14-Apr-2021

757 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements