Confusion with string.replace()

Chris Barker chrishbarker at home.net
Fri Oct 26 13:37:52 EDT 2001


Joseph Wilhelm wrote:

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

This has nothing top do with replace(), and eveything to do with
Python's default interpretation of sting constants. \ is an escape for
python also, so your first version:"\'" just creates a "'". The second
version "\\'" is correct, as the \\ is the correct code for a \. You are
getting confused by the command line representation. There are two
methods for turning a Python object into a string for presentation:

repr()  Which creates a string representation of an object that can be
used to re-construct the object. the goal is that eval(repr(x)) == x

str() creates a string representation that is designed for humans to
read. At the command line, if you just type the name of a variable, what
you get is repr(var). Ifyou use a print statement, you get the pretty
version. Some examples:

>>> s = "\'"
>>> print s
'
>>> s
"'"
# so you have only the ' character.
>>> s = "\\'"
>>> s
"\\'"
>>> # now it looks like you have two slashes, but you don't really:
...
>>> len(s)
2
>>> print s
\'
>>>

Another option is to use "raw" strings. You get these be putting an r in
front of the string. When you do this, you are telling Python to ignore
special escape sequences, and jsut taek what you types literally. this
is very handy for things like what you are doing, creating a string that
with escapes to be interpreted by something else. It is used a lot with
regexes.

>>> s = r"/'"
>>> s
"/'"
>>> print s
/'
>>>

So your code could be:

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

By the way, in newer version of Python, you can use string methods
rather than the string module:

b = a.replace("'",r"\'")

Hope that helps

-Chris




-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list