Confusion with string.replace()

Matt canimalatmydejadotcom at nospam.com
Fri Oct 26 12:56:24 EDT 2001


"Joseph Wilhelm" <jwilhelm at outsourcefinancial.com> wrote in
news:mailman.1004110827.23550.python-list at python.org: 

> 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?
> 
> --Joseph Wilhelm

In MS SQL, you can double up the apostrophe instead of escaping it, and 
your query will treat the double apostrophe as an escaped single apos:

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

I think this is a standard SQL construct, and will work on other platforms 
as well.

Matt



More information about the Python-list mailing list