How to Remove All Whitespace From String in Python

In this tutorial, learn how to remove all whitespace from a string using Python. The short answer is: use the Python replace() function to remove the whitespaces from the string.

A string may contain many numbers of whitespace in Python. On some place of your programming, you may require to remove all these white spaces in Python. To remove all the whitespaces, you have to check and understand each example given below.

Remove All Whitespace From String Using Replace() in Python

To remove all whitespace from the string, you can use Python replace() function. The replace() function requires two arguments to pass and replace all the whitespaces. The first argument is the space while the second argument is without space in double quotes.

You have to use the below-given example to replace and get rid of white spaces in the string in Python. You have to use the Python print statement to print the string with no whitespaces.

Output

Howareyoutoday?

The above example gives output with no spaces in the string characters. This is the one method in Python. However, you can also use the Python regular expression to erase every spaces. To perform this task using a regular expression, read further.

Using Regular Expression to Get Rid of Spaces From String in Python

If you want to erase all the spaces from the string using regular expression in Python. You have to use the below-given example. Copy the below-given example on your Python file and execute this Python code.

After execution, you will get a string with no spaces in the characters. So, let’s see this method in the example given below.

Output

Howareyoutoday?

The above example showing the output with no extra spaces in the string characters.

Now, it depends upon you whether you want to erase spaces using replace() or regular expression. Both functions work great in Python and remove all the whitespace from your string.

You may also like to read

Hope, you like this tutorial of how to remove all whitespace from the string in Python. If you have any query regarding the tutorial, please comment below.

References

Also tell me, which method you are using to remove white spaces from your string in Python.

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.