I want to replace all occurrences of && with and.
For example, x&& && && should become x&& and and.
I tried re.sub(' && ', ' and ', 'x&& && && '), but it didn't work, the first && already consumed the whitespace so the second one didn't match.
Then I thought of non-capturing group and tried but failed again.
How can I solve this problem?
You could use non-word boundaries here.
>>> re.sub(r'\B&&\B', 'and', 'x&& && &&')
'x&& and and'
(?:^|(?<=\s))&&(?=\s|$)
Use lookarounds.Do not consume space just assert.See demo.
https://regex101.com/r/sS2dM8/39
re.sub('(?:^|(?<=\s))&&(?=\s|$)', 'and', 'x&& && &&')
Output:'x&& and and'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With