Remove all whitespace in a string

I want to eliminate all the whitespace from a string, on both ends, and in between words.

This only eliminates the whitespace on both sides of the string:

>>> "  hello  apple  ".strip()
'hello  apple'

How do I remove all whitespace?

13 s
13

If you want to remove leading and ending spaces, use str.strip():

>>> "  hello  apple  ".strip()
'hello  apple'

If you want to remove all space characters, use str.replace() (NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace):

>>> "  hello  apple  ".replace(" ", "")
'helloapple'

If you want to remove duplicated spaces, use str.split() followed by str.join():

>>> " ".join("  hello  apple  ".split())
'hello apple'

Leave a Comment