string.replace

David Goodger dgoodger at bigfoot.com
Sat May 6 04:50:24 CEST 2000


on 2000-05-05 13:12, rei05 at gmx.de (rei05 at gmx.de) wrote:
>> On Fri, 5 May 2000 rei05 at gmx.de wrote:
>>> so i tried string.replace(s,"'","\'"), but this doesn`t work.
>> 
> sorry, i forgot to mention, that i tried:
>> 
>> string.replace(s,"'","\\'")
>> 
> too, but the result of this is like the following:
> 
>>>> import string
>>>> s="asdasd'a'asddads"
>>>> string.replace(s,"'","\\'")
> "asdasd\\'a\\'asddads"
> 
> and i wish to have ...\'a\'..., not ...\\'a\\'...

Try this:

    >>> import string
    >>> s="asdasd'a'asddads"
    >>> print string.replace(s,"'","\\'")
    asdasd\'a\'asddads

When you entered just:

    >>> string.replace(s,"'","\\'")

(i.e., without the "print" statement), because you're in the interactive
interpreter, what you were actually saying was something like:

    >>> print repr(string.replace(s,"'","\\'"))

string.replace is a function which returns a new string with the results of
the replacement. (string.replace does *NOT* do anything to s itself! Strings
in Python are immutable; they cannot be changed in-place. Repeat until
understood. :-) And so Python shows you a representation of the new string,
because you haven't told it what to do with the return value. Python's
*representation* of a backslash is "\\", because that's what you'd have to
type to get a single backslash. "\\" is simply an artefact of the
interactive interpreter telling it like it is! To prove all of the above, do
this:

    >>> new_s = string.replace(s,"'","\\'")
    >>> new_s
    "asdasd\\'a\\'asddads"
    >>> print new_s
    asdasd\'a\'asddads
    >>> new_s[5]
    'd'
    >>> print new_s[5]
    d
    >>> new_s[6]
    '\\'
    >>> print new_s[6]
    \
    >>> new_s[7]
    "'"
    >>> print new_s[7]
    '

Note the presence (or absence) of quotation marks when not using (or when
using) "print".

In a program, you'd likely write something like the first line above (new_s
= ...) anyhow, since you probably want to do something with the new string.

-- 
David Goodger    dgoodger at bigfoot.com    Open-source projects:
 - The Go Tools Project: http://gotools.sourceforge.net
 (more to come!)




More information about the Python-list mailing list