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?
If you want to remove leading and ending spaces, use
sentence = ' hello apple' sentence.strip() >>> 'hello apple'
If you want to remove all spaces, use
sentence = ' hello apple' sentence.replace(" ", "") >>> 'helloapple'
If you want to remove duplicated spaces, use
sentence = ' hello apple' " ".join(sentence.split()) >>> 'hello apple'
To remove only spaces use
sentence = sentence.replace(' ', '')
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
sentence = sentence.strip()