1

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?

3 Answers 3

6

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
3
  • Yes, you're right! Unfortunately, this oddity is causing my nose doctests to fail, as I have a doctest embedded, and the doctest interpreter gets the \\ back. How do I get the interpreter to stop being silly?
    – cflewis
    Sep 27, 2011 at 0:21
  • You don't. Either use print in the doctest, or use '\\'. the whole "point" of doctests is to look the same as interactive use. Say... are you using a raw string in that doctest? You should be! Sep 27, 2011 at 0:25
  • Don't forget that the docstring is itself a string, so it will undergo one level of "unescaping" before being run as a doctest. Sep 27, 2011 at 0:33
4

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.

1
  • 1
    Never mind... I'll upvote yours because someone downvoted mine.
    – Mark Byers
    Sep 27, 2011 at 0:25
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.