I'm curious about \ processing in Python regular expressions.

Asked 2 years ago, Updated 2 years ago, 86 views

import re
b = 'Yaho\'
a = re.compile('\\')

print(re.sub(a, '@', b)

What I was expecting was a yahoo@, but there's a compilation error If you want to do what I expected, re.compile('\\') Why do I have to write 3 letters when I have to do this

python regex compile

2022-09-22 19:51

1 Answers

Hello, everyone

import re

b = 'Yay\\'
a = re.compile('\\\\')

print(re.sub(a, '@', b))

You can do it like this, but this... I searched and found that the string parser removes two backslashes. So I added one to recognize it as just a slash, plus two to be removed from the parser, so it became four ;;

import re

b = 'Yay\\'
a = re.compile(r'\\')

print(re.sub(a, '@', b))

Or, if you put an "r" in front of the original string, you can get what you want because the parser doesn't touch it Yay!


2022-09-22 19:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.