inserting \ in regular expressions [solved]

Ross Boylan ross at biostat.ucsf.edu
Sat Nov 5 15:03:27 EDT 2011


On Wed, 2011-10-26 at 12:48 -0700, Ross Boylan wrote:
> I want to replace every \ and " (the two characters for backslash and
> double quotes) with a \ and the same character, i.e.,
> \ -> \\
> " -> \"
I'd like to thank Ian, Dave, MRAB, and John for their helpful responses.
I hadn't realized the interpreter was giving me the repr, and that
differed from the str.

I've since found one other solution: email.utils.quote() does exactly
the substitution I was looking for--not surprising, since I was doing it
for email.

Here's my little test program:
#! /usr/bin/python
import email, email.utils, re
s0 = r'I am " a silly \quote'
print s0
print re.sub(r'(\\|")', r'\\\1', s0)
print email.utils.quote(s0)

Output
I am " a silly \quote
I am \" a silly \\quote
I am \" a silly \\quote

Ross





More information about the Python-list mailing list