Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Machine Learning by (19k points)

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?

1 Answer

0 votes
by (33.1k points)
edited by

To remove leading and ending spaces, use str.strip():

sentence = ' hello apple' 

sentence.strip() 

>>> 'hello apple'

To remove all spaces, use str.replace():

sentence = ' hello apple' 

sentence.replace(" ", "") 

>>> 'helloapple'

To remove duplicated spaces, use str.split():

sentence = ' hello apple' 

" ".join(sentence.split()) 

>>> 'hello apple'

Hope this answer helps you!

If you want to learn  Python for Data Science then you can watch this Python tutorial:

Related questions

Browse Categories

...