Remove all whitespace from a String in Python

avatar

Borislav Hadzhiev

Last updated: Aug 20, 2022

banner

Photo from Unsplash

Remove all whitespace from a String in Python #

Use the re.sub() method to remove all whitespace from a string, e.g. result = re.sub(r'\s+', '', my_str). The re.sub() method will remove all whitespace characters from the string by replacing them with empty strings.

main.py
import re my_str = ' one two ' # ✅ Remove all whitespace result = re.sub(r'\s+', '', my_str) print(result) # 👉️ 'onetwo' # ✅ Revemove all spaces result = my_str.replace(' ', '') print(result) # 👉️ 'onetwo' # ✅ Remove leading and trailing whitespace result = my_str.strip() print(result) # 👉️ 'one two' # ✅ Remove all whitespace result = ''.join(my_str.split()) print(result) # 👉️ 'onetwo' # ✅ Replace multiple, consecutive whitespaces with a single space result = ' '.join(my_str.split()) print(result) # 👉️ 'one two'

The first example uses the re.sub() method to remove the whitespace characters from the string.

The re.sub method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.

main.py
import re my_str = ' one two ' # ✅ Remove all whitespace result = re.sub(r'\s+', '', my_str) print(result) # 👉️ 'onetwo'

If the pattern isn't found, the string is returned as is.

The \s character matches unicode whitespace characters like [ \t\n\r\f\v].

The plus + is used to match the preceding character (whitespace) 1 or more times.

We remove all whitespace characters from the string by replacing them with empty strings.

To remove all spaces from a string, use the str.replace() method, e.g. result = my_str.replace(' ', ''). The replace() method will remove all spaces from the string by replacing them with empty strings.

main.py
my_str = ' one two ' result = my_str.replace(' ', '') print(result) # 👉️ 'onetwo'

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

The method doesn't change the original string. Strings are immutable in Python.

Note that this approach only removes spaces from the string, it doesn't remove tabs and newline characters.

Use the str.strip() method to remove the leading and trailing whitespace from a string, e.g. result = my_str.strip(). The str.strip() method returns a copy of the string with the leading and trailing whitespace removed.

main.py
my_str = ' one two ' result = my_str.strip() print(result) # 👉️ 'one two'

The str.strip method removes the leading and trailing whitespace from the string.

If you need to replace multiple, consecutive whitespace characters with a single space, use the str.split() and str.join() methods.

main.py
my_str = ' one two ' result = ' '.join(my_str.split()) print(result) # 👉️ 'one two'

The str.split() method splits the string into a list of substrings using a delimiter.

When the str.split() method is called without a separator, it considers consecutive whitespace characters as a single separator.
main.py
my_str = ' one two ' # 👇️ ['one', 'two'] print(my_str.split())

When called without an argument, the str.split() method splits on consecutive whitespace characters (e.g. \t, \n, etc), not only spaces.

The next step is to use the str.join() method to join the list of strings with a space separator.

main.py
my_str = ' one two ' result = ' '.join(my_str.split()) print(result) # 👉️ 'one two' print(' '.join(['one', 'two'])) # 👉️ 'one two'

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

You can also use this approach to remove all whitespace from the string.

main.py
my_str = ' one two ' result = ''.join(my_str.split()) print(result) # 👉️ 'onetwo'

We used an empty string as the separator when joining the elements to remove all whitespace characters from the string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.