Confusion with string.replace()
gbreed at cix.compulink.co.uk
gbreed at cix.compulink.co.uk
Fri Oct 26 12:51:30 EDT 2001
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, "'", "\'" )
> >>> b
> "a'b"
> >>> b = string.replace( a, "'", "\\'" )
> >>> b
> "a\\'b"
> >>>
>
> I just can't seem to wrap my brain around why it's doing that. Can
> somebody
> explain that, or perhaps provide an easier option for preparing a SQL
> statement?
The second example is doing what you thing is should do. Try print b to
see that this is so. But string.replace(a, "'", "''") is correct SQL.
The best option is to use a library to do the dirty work for you.
Graham
More information about the Python-list
mailing list