Remove all whitespace in a string in Python


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

I have this Python code:

def my_handle(self):
    sentence = ' hello  apple  '

But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace?

3/14/2018 10:17:31 AM

Accepted Answer

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

sentence = ' hello  apple'
>>> 'hello  apple'

If you want to remove all spaces, use str.replace():

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

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

sentence = ' hello  apple'
" ".join(sentence.split())
>>> 'hello apple'
11/23/2016 12:32:31 PM

To remove only spaces use str.replace:

sentence = sentence.replace(' ', '')

To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:

sentence = ''.join(sentence.split())

or a regular expression:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

If you want to only remove whitespace from the beginning and end you can use strip:

sentence = sentence.strip()

You can also use lstrip to remove whitespace only from the beginning of the string, and rstrip to remove whitespace from the end of the string.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow