Confusion with string.replace()

Nicholas FitzRoy-Dale wzdd at lardcave.net
Fri Oct 26 12:47:58 EDT 2001


On 26 Oct, Joseph Wilhelm wrote:
> I'm getting some really strange behaviour from string.replace(), and I was
> wondering if somebody could help explain this to me. All I'm trying to do is
> escape single quotes in a string for a SQL query, but here's an example of
> what I'm getting:
> 
>>>> import string
>>>> a = "a'b"
>>>> b = string.replace( a, "'", "\'" )

You replace ' with an escaped ', which is the same as a plain ' here.

>>>> b
> "a'b"
>>>> b = string.replace( a, "'", "\\'" )
>>>> b
> "a\\'b"

Yes, but if you:
>>> len (b)
4
>>> b[1]
'\\'

What you're doing is replacing ' with a \ followed by a '. You have to
quote the backslash in the Python string, and it's replaced by a single
backslash in the new string. However printing the string causes the
backslash to be quoted again.

> I just can't seem to wrap my brain around why it's doing that. Can somebody
> explain that

Did that make any sense? :)

-- 
- Nicholas FitzRoy-Dale
http://www.lardcave.net

I'm thinking of getting a pet cheese.  I already have the cheese food.
- http://www.enweirdenment.org/cgi-bin/cube-hof.html





More information about the Python-list mailing list