+ 11
how to remove all occurences of exaxtly 2 spaces in a string with regular expressions in python, even if there are sections ...
... which consist of more than 2 spaces. I have done an example here https://code.sololearn.com/cm9Q6a23XeCh/?ref=app , but I want to know how to do the part in line 12 (d = ...) not with list comprehension but with the substitute-function of the re-module directly.
4 Antworten
+ 5
To remove occurrence of double spaces at the beginning and at the end of string, a little change is necessary :
r'(\b|\A)\s{2}(\b|\Z)'
+ 6
re.sub(r'\b\s{2}\b', '', a)
Explanation:
\b means an invisible "boundary" that encloses each word (non-whitespace) in the string
\s{2} means exactly 2 whitespaces
usually it works best to mark the pattern as raw string (prefix r before the opening apostrophe/quote) so that escape characters are properly recognized by the regexp engine
+ 5
Tibor Santa
Thank you very much! 👍😊
+ 5
thank you Tibor Santa and Qasem for your solutions. The final code is here:
https://code.sololearn.com/cyUEKcfHnS4X/?ref=app