Spaces are nothing more than a string in Python. To remove space from a Python string, you must treat it the same way you have removed any other character from a string. So if you want to learn how to remove extra spaces from a Python string, this article is for you. In this article, I’ll show you a quick tutorial on how to write a Python program to remove spaces from a Python string.
Python Program to Remove Spaces
When entering values to user input in real-time, users sometimes leave extra spaces in their names, addresses, or other input fields. To properly store data collected from a user, you need to make sure that your app removes any extra spaces left by the user to avoid misinformation. So here’s how you can easily write a Python program to remove spaces from a string:
text = "Hi, My Name is Aman" new_text = text.replace(" ", "") print(new_text)
Hi, My Name is Aman
In the code above, I first introduced a variable as text where you can see some extra space. As mentioned before, a space in Python or any other programming language is treated the same as other characters in a string, so in the next line, I introduced a new variable as new_text where I have stored the same string by replacing the extra spaces with a single space.
So this is how you can easily remove any number of extra spaces from a Python string. It is very important to implement such small functions in your application, especially if it is designed to collect data from a user because when entering user input in real-time, users sometimes leave extra spaces in their names, addresses or any other input field. Hope you liked this article on how to write a Python program to remove spaces from a string. Please feel free to ask your valuable questions in the comments section below.