
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- Replacing space with a hyphen in C++
- Java regex program to split a string at every space and punctuation.
- Python Program to Replace all Occurrences of ‘a’ with $ in a String
- Remove new lines from a string and replace with one empty space PHP?
- C++ program to replace all occurrences of string AB with C without using extra space
- Python Program to Replace the Spaces of a String with a Specific Character
- How to set a string with hyphen and numbers in MySQL varchar?
- Replace every consonant sequence with its length in the given string
- C++ Program to find and replace in a string
- How to replace all occurrences of a string with another string in Python?
- C# program to replace all spaces in a string with ‘%20’
- Hyphen string to camelCase string in JavaScript
- How to replace multiple spaces with a single space in C#?
- Replace Tab with space in SAP ABAP
- How to replace “and” in a string with “&” in R?

Advertisements