Modifying escape sequences in strings
Thomas Philips
tkpmep at hotmail.com
Tue Mar 2 11:14:29 EST 2004
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