How to remove all white spaces in a string in Python

If you want to truly remove any space in a string, leaving only the characters, the best solution is to use a regular expression.

You need to import the re module that provides regular expression operations.

Notice the \s represents not only space ' ', but also form feed \f, line feed \n, carriage return \r, tab \t, and vertical tab \v.

In summary, \s = [ \f\n\r\t\v].

The + symbol is called a quantifier and is read as ‘one or more’, meaning that it will consider, in this case, one or more white spaces since it is positioned right after the \s.

import re

phrase = ' Do   or do    not   there    is  no try   '

phrase_no_space = re.sub(r'\s+', '', phrase)

print(phrase)
# Do   or do    not   there    is  no try   

print(phrase_no_space)
#Doordonotthereisnotry

The original variable phrase remains the same, you have to assign the new cleaned string to a new variable, phrase_no_space in this case.

Watch on Youtube

You can also watch this content on Youtube: