I want to eliminate all the whitespace from a string, on both ends, and in between words.
I have this Python code:
JavaScript
x
4
1
def my_handle(self):
2
sentence = ' hello apple '
3
sentence.strip()
4
But that only eliminates the whitespace on both sides of the string. How do I remove all whitespace?
Advertisement
Answer
If you want to remove leading and ending spaces, use str.strip()
:
JavaScript
1
3
1
>>> " hello apple ".strip()
2
'hello apple'
3
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):
JavaScript
1
3
1
>>> " hello apple ".replace(" ", "")
2
'helloapple'
3
If you want to remove duplicated spaces, use str.split()
followed by str.join()
:
JavaScript
1
3
1
>>> " ".join(" hello apple ".split())
2
'hello apple'
3