+ 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.

2nd Nov 2019, 6:39 AM
Jan Markus
4 Answers
+ 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)'
2nd Nov 2019, 12:17 PM
Qasem
+ 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
2nd Nov 2019, 7:28 AM
Tibor Santa
Tibor Santa - avatar
+ 5
Tibor Santa Thank you very much! 👍😊
2nd Nov 2019, 7:52 AM
Jan Markus
+ 5
thank you Tibor Santa and Qasem for your solutions. The final code is here: https://code.sololearn.com/cyUEKcfHnS4X/?ref=app
3rd Nov 2019, 3:05 AM
Jan Markus