Python inserting backslashes during regular expression
I'm trying to do a regex to substitute in a backslash, but Python seems to be inserting a double-backslash, and I can't make it stop!
>>> re.sub('a', '\\ b', 'a')
'\\ b'
Double backslash is supposed to be backslash (escape + backslash = backslash), but it ends up being literal.
If I remove 开发者_运维技巧the double slash, it doesn't print one at all:
>>> re.sub('a', '\ b', 'b')
'b'
How do I get Python to sub in just one backslash?
It's not inserting a double backslash. That is simply the interactive interpreter showing the string as a string literal. Use print
to see the actual string:
>>> "\\n"
'\\n'
>>> print "\\n"
\n
I suppose this isn't an answer (I second Liquid_Fire), but a suggestion:
"\\b" -> \b
r"\b" -> \b
Use r"" raw strings to simplify backslashes in Python.
Prefix the string with the letter "r". This instructs Python to interpret the string literally.
For your code:
re.sub('a', r'\ b', 'a')
You will often find "r" used with Python and regular expressions.
精彩评论