Last Updated on December 27, 2020 by Roshan Parihar
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. In 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 the Python replace()
function. The 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.
1 2 |
myStr = 'How are you today?'; print(myStr.replace(" ", "")); |
Output
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 space. 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.
1 2 3 |
import re; myStr = 'How are you today?'; print(re.sub(' ','',myStr)); |
Output
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
- How to access string character by index using Python
- convert all string to lowercase in Python
- Create a string variable in Python
- Combine two string variables in Python
I hope you like this tutorial on how to remove all whitespace from the string in Python.
References