Python Program to Remove Spaces From a Given String
In this example, we will write a simple program to take input string from the user and remove the space from the given string. To better understand this example, make sure you have knowledge of the following tutorials:-
Contents
Python Program to Remove Spaces From a Given String using for loop
inputstr = input("Enter your string: ") new_string = "" for char in inputstr: if char != " ": new_string += char print("New String after space removed:- ", new_string)
The output of the above program is:-
New String after space removed:- MyNameisJohnDoe
Python Program to Remove Spaces From a Given String using replace() method
inputstr = input("Enter your string: ") new_string = inputstr.replace(" ", "") print("New String after space removed:- ", new_string)
The output of the above program is:-
New String after space removed:- MyNameisJohnDoe
Program Explanation
The string methods provide an easy way to operate on the strings in Python. Here, the replace method is used to replace the spaces with a non-empty character.