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

on 2000-05-05 13:12, rei05 at (rei05 at wrote:
>> On Fri, 5 May 2000 rei05 at 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,"'","\\'")

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

    >>> new_s = string.replace(s,"'","\\'")
    >>> new_s
    >>> print new_s
    >>> new_s[5]
    >>> print new_s[5]
    >>> 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    Open-source projects:
 - The Go Tools Project:
 (more to come!)

More information about the Python-list mailing list