Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Why re.sub() is actually keeping the replace pattern

I though re.sub() is for replacemenmt. For example:

import re
print(re.sub('ab', 'ad', 'abc'))

The output is ‘adc’ of course. However, when I try this:

s = "hello world!"
print(re.sub("[^A-Za-z]", "+", s))

The output is weirdly ‘hello+world+’ instead of ‘+++++ +++++!’. It actually keeps all the letters rather than replace then with "+". Idk why…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

remove the ^, it anchors to a single point, source:

Code:

s = "hello world! how are you?"
print(re.sub("[A-Za-z]", "+", s))

you can find it in the documentation

Output:

+++++ +++++! +++ +++ +++?
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading