Remove all whitespace in a string in Python

592    Asked by bhagwatidubey in Python , Asked on Jul 8, 2021

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 python remove all spaces from string?


Answered by Camellia Kleiber

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

sentence = ' hello apple'
sentence.strip()
>>> 'hello apple'

If you want to remove all spaces from string, 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'

Your Answer

Interviews

Parent Categories