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

Advertisements

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: ""

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')

Leave a ReplyCancel reply