Confusion with string.replace()

-RZ Dick.Zantow at lexisnexis.com
Fri Oct 26 13:02:49 EDT 2001


"Joseph Wilhelm" <jwilhelm at outsourcefinancial.com> wrote in message
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


Things are not always what they appear

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







More information about the Python-list mailing list