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:-

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:-

Enter your string: My Name is John Doe
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:-

Enter your string: My Name is John Doe
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.

SHARE Python Program to Remove Spaces From a Given String

You may also like...

Leave a Reply

Your email address will not be published.

Share