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

Why re.sub(r'\n$', '', "\n\n") gives "" instead of "\n"?

Is this intended?
Logically re.sub(r’\n$’, ”, "\n\n") should give "\n". But when I try, it gives me "".
Can anyone explain it to me? Thanks.

Verified in Python 3.10.12

re.sub(r'\n$', '', "\n\n") # ""

Expect: "\n"
Actual: ""

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

In contrast:

re.sub(r'a$', '', "aa") # "a"

The result is "a" as expected.

>Solution :

\n and $ basically match the same positions. If you wanted to say "\n" adjacent to the end of the input string" instead of … "adjacent to end of line" (which of course trivially every \n will match), the notation for that is

re.sub(r'\n\Z', '', '\n\n')
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