- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements