How do I get rid of all the gaps at the beginning, middle, and end of a string? My code only removes the spaces at the beginning and end, but I want to remove all the gaps
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
There are several ways to truncate blank characters. I'm not sure if the space I want to erase means space or all the space characters such as opening letters, so I'll write them all down.
sentence = ' hello apple'
sentence.strip() #'hello apple'
sentence = ' hello apple'
sentence.replace(" ", "") #'helloapple'
import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)
#or
sentence = ' hello apple\t\t\n\n\n\n'
''.join(sentence.split()) #'helloapple'
sentence = ' hello apple'
" " ".join(sentence.split()) # 'hello apple'
© 2024 OneMinuteCode. All rights reserved.