Reputation: 1
Confused over the purpose of "r". As i understand it helps to read as a normal character than its usage as an escape character
I tried multiple codes as follows and all are giving the same output. This is making me confused on the real interpretation of "r". While i agree with first 3 lines of code.Fourth one is where im confused.
1.re.sub("n\'t", " not", " i am n't happy")
2.re.sub("n\'t", " not", " i am n\'t happy")
3.re.sub(r"n\'t", " not", " i am n\'t happy")
4.re.sub(r"n\'t", " not", " i am n't happy")
Result of all 4 above is :'
' i am not happy'
import re
re.sub(r"n\'t", " not", " i am n't happy")
Given that i have used "r" i expected the backslash to be treated as a characters and not escape character
Actual Output ' i am not happy'
Expected Output ' i am n't happy'
Upvotes: 0
Views: 74
Reputation: 31260
The thing is that there are two layers of -escaping: in the string literal, and in the regex. And in neither does \'
have a special meaning, and it's just treated as '
.
What using r""
does here is to skip the first string-literal escaping, so that a literal \
is included in the string, but then the regex sees the string \'
and just treats it as '
.
So all four come down to replacing n't
with not
.
You still need double backslashes to match a literal backslash.
Upvotes: 1