Remove spaces from a string in Python

A string can contain one or more spaces that we often may want to remove. May be some unwanted spaces comes with our string. We may remove the space from the right side or from the left side or from both right and left. We may also need to remove all spaces completely from the string.

So in this tutorial, I am going to show you how to remove spaces from a string in Python. Continue reading to see how we are going to remove spaces that may be in the various position of a string.

Remove spaces from the left and right sides of a string

Python has some string methods that we can use to remove the spaces from left and right side of a string. These are lstrip() and rstrip() methods.

Below is the code to remove spaces from the left side of the string:

string = "  codespeedy   "
# remove spaces from left
str_wt_space = string.lstrip()
print(str_wt_space)

The above code will remove all the spaces from the left side of the string. The output is given below:

codespeedy

And now, below is the code snippet using the Python rstrip() method to remove spaces from the right side of the string:

string = "    codespeedy     "
# Remove spaces from right side of the string
str_wt_space = string.rstrip()
print(str_wt_space+"....")

The above code will give the output that is given below:

    codespeedy....

You can notice that I have placed some dots while printing the output so that we can understand that the spaces have been removed from the right side and no space left.

 

Also, read:

 

Remove spaces from both left and right

Using the Python strip() method, we can remove spaces from both left and right sides of the string. Below is the code:

string = "    codespeedy    "
str_wt_space = string.strip()
print(str_wt_space+"....")

And below is the output:

codespeedy....

Of course, we can do this using lstrip() and rstrip() method. But we need to write some extra lines of code. So it is easier to remove both left and right spaces from the string using the Python strip() method.

 

Remove all spaces from string using replace() method

The above methods we have discussed are not able to remove spaces from the middle of the string. For example, if we want to remove all spaces from the string “code   speedy” using the previous methods, then it will not be able to remove all the spaces.

To overcome the problem we will use replace() method of Python. Below is an example:

string = "    code   speedy    "
str_wt_space = string.replace(" ", "")
print(str_wt_space+"....")

The output of the above code snippet is:

codespeedy....

So we can see that all the spaces from our string have been removed using Python replace() method.

I hope you understand the topic of this post and learn how to remove spaces from a string in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *