inserting \ in regular expressions

Ian Kelly ian.g.kelly at gmail.com
Wed Oct 26 16:26:45 EDT 2011


On Wed, Oct 26, 2011 at 1:48 PM, Ross Boylan <ross at biostat.ucsf.edu> wrote:
> Or perhaps I'm confused about what the displayed results mean.  If a
> string has a literal \, does it get shown as \\?

In the repr, yes.  If you try printing the string, you'll see that it
only contains one \.

By the way, regular expressions are overkill here.  You can use the
str.replace method for this:

>>> print(r'Silly \ " quote'.replace('\\', '\\\\').replace('"', r'\"'))
Silly \\ \" quote

Cheers,
Ian



More information about the Python-list mailing list