Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all whitespace in a string

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?

like image 203
Gayan Kalanamith Avatar asked Nov 25 '11 13:11

Gayan Kalanamith


1 Answers

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 space characters, use str.replace():

(NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace)

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

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

sentence = ' hello  apple' " ".join(sentence.split()) >>> 'hello apple' 
like image 182
Cédric Julien Avatar answered Oct 10 '22 22:10

Cédric Julien