Modifying escape sequences in strings

Larry Bates lbates at swamisoft.com
Tue Mar 2 11:40:48 EST 2004


The problem is that the backslash (\) has special
meaning to Python.  It means that the next character
is escaped (has special meaning).

Try following:

x=x.replace("\\n","\n")

This works for me.

-Larry


"Thomas Philips" <tkpmep at hotmail.com> wrote in message
news:b4a8ffb6.0403020814.283e64d6 at posting.google.com...
> I have been playing around with reading strings with embedded escape
> sequences from files both using readline() and codecs.open() and have
> a question.I create a file "test.txt" with exactly one line:
> 1\na\n\n2\n\n3
>
> I then open test.txt and then read it using readline():
> >>> input_file=file("test.txt")
> >>> x=input_file.readline()
>
> >>> x
> >>> 1\\na\\n\\n2\\n\\n3
> >>> print x
> >>> 1\na\n\n2\n\n3
>
> The readline has escaped the backslashes, so that they print
> correctly. I tried to replace the double backslashes with single
> backslashes to escape the "n"
> >>> x.replace("\\","\")
>
> SyntaxError: EOL while scanning single-quoted string
> >>>
>
> How can I replace the escaped backslash with a backslash? I realize
> that I can solve the problem by reading the file using
> codecs.open("test.txt","r","string_escape") as suggested by Peter
> Otten. I'm trying to do the same thing in different ways to better
> understand Python
>
> Sincerely
> Thomas Philips





More information about the Python-list mailing list