HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

Remove all whitespace in a string

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringallwhitespaceremove

Problem

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 '
sentence.strip()


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

Solution

If you want to remove leading and ending whitespace, 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 all whitespace and then leave a single space character between words, use str.split() followed by str.join():

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


If you want to remove all whitespace then change the above leading " " to "":

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

Code Snippets

>>> "  hello  apple  ".strip()
'hello  apple'
>>> "  hello  apple  ".replace(" ", "")
'helloapple'
>>> " ".join("  hello  apple  ".split())
'hello apple'
>>> "".join("  hello  apple  ".split())
'helloapple'

Context

Stack Overflow Q#8270092, score: 2418

Revisions (0)

No revisions yet.