Remove spaces from a string in Python

A string can contain one or more spaces which we often may want to remove. So in this post, 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 left and right side 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 Python rstrip() method to remove spaces from 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 spces has been removed.



 

Also, read:

 

Remove spaces from both left and right

Using Python strip() method, we can remove spaces from both left and right side 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 extra line of codes. So it is easier to remove both left and right spaces from string using Python strip() method.

 

Remove all spaces from string using replace() method

The above methods we have discussed is 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”, 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 above code snippet is:

codespeedy….

So we can see that all the spaces from our string has been removed using 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 *