Modifying escape sequences in strings

Jeff Epler jepler at unpythonic.net
Tue Mar 2 11:39:58 EST 2004


If you want to translate two backslashes into a single backslash,
have to write
    x.replace("\\\\", "\\")
the first is a string of length 2 and the second is a string of length
1.  I don't know why the tutorial doesn't cover this point explicitly
(http://python.org/doc/current/tut/node5.html#SECTION005120000000000000000)
but the language reference does (http://python.org/doc/current/ref/strings.html)
... but there are no sequences of two backslashes in the strings you
were working with.

However, I think that referring to "escaped backslashes" in the string
you read shows that there's some other misunderstanding of what is going
on.  Is your final goal to turn the backslash-n sequences into actual
newlines, or what?  If this is your goal, then you should use the
"string_escape" codec in Python 2.3:
    >>> '\\n'.decode("string_escape")
    '\n'
This took a string containing backslash-n and returned a string
containing a newline character.

Jeff




More information about the Python-list mailing list