I want to remove all blank characters in the string, but only the first and last spaces are removed

Asked 1 years ago, Updated 1 years ago, 86 views

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()

python trim removing-whitespace

2022-09-22 12:44

1 Answers

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'


2022-09-22 12:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.