Confusion with string.replace()

Paul Winkler slinkp23 at yahoo.com
Fri Oct 26 12:32:47 EDT 2001


On Fri, 26 Oct 2001 08:39:00 -0700, Joseph Wilhelm
<jwilhelm at outsourcefinancial.com> 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"

When you examine a string this way at the interactive prompt, python
will show you the escape sequences (if necessary) in the string so you
can tell what exactly it's made of.  When you see "a\\'b", that's what
you wanted: a literal backslash followed by a single quote, and python
is telling you so, but not in the way that you expected.

Consider this:
>>> "hello\t"
'hello\tworld'
>>> print "hello\tworld"
hello   world
>>> "\'"  # escaped single quote - evaluates to single quote
"'"
>>> print "\'"
'
>>> "\\'" # escaped backslash - evaluates to literal backslash
"\\'"
>>> print "\\'"
\'


-- Paul Winkler



More information about the Python-list mailing list