Problems replacing \ with \\

MRAB google at mrabarnett.plus.com
Mon Apr 21 20:08:08 EDT 2008


On Apr 21, 11:48 pm, "samsli... at gmail.com" <samsli... at gmail.com>
wrote:
> Hi...
>
> Here's a weird problem...I'm trying to escape a bunch of data to put
> into a database.
>
> Here's what I have:
>
> def escape(string):
>     """
>     Escape both single quotes and blackslashes
>     >>> x = r"fun\fun"
>     >>> escape(x)
>     'fun\\\\fun'
>     """
>     string = string.replace('\\', '\\\\')
>     return string
>
> Now the commands in the doctest work when I type them by hand into the
> python interpreter!>>> x = r"fun\fun"
> >>> escape(x)
>
> 'fun\\\\fun'
>
> But they don't work when I actually run them with doctest:
> Failed example:
>     escape(x)
> Expected:
>     'fun\\fun'
> Got:
>     'fun\x0cun'
>
> Why?
>
> Thanks!

Your doctest is in a triple-quoted string which contains the line:

>>> x = r"fun\fun"
             ^^

which is the same as:

>>> x = r"fun\x0cun"
             ^^^^

If you wrap a raw string in just quotes that is isn't a raw string any
longer!

HTH



More information about the Python-list mailing list