Modifying escape sequences in strings

T

Thomas Philips

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():
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"
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
 
J

Jeff Epler

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'
This took a string containing backslash-n and returned a string
containing a newline character.

Jeff
 
L

Larry Bates

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top