Reputation: 331
I'm new to Python and I'm using one of the examples I found here to read lines from a file and print them. What I don't understand is why the interpreter ignores \n
escape sequence:
Which of the following are components you might find inside a PC? (Select all correct answers.)
A. CPU
B. Motherboard
C. Keyboard
Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM
questions_fname="Test.txt"
with open(questions_fname, 'r') as f:
questions = [line.strip() for line in f]
for line in questions:
print (line)
f.close()
The result I get is strings like:
Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM
I was just looking for a simple way of formatting long lines to fit the screen.
Upvotes: 1
Views: 11707
Reputation: 133
\
is an escape character only in Python script, not in text files. When reading text files, Python converts all backslashes to \\
, so when reading the file, \n
becomes \\n
which is not a newline character
Upvotes: 0
Reputation: 20744
Try the following code to get the wanted behaviour...
questions_fname = "Test.txt"
with open(questions_fname) as f:
for line in f:
line = line.rstrip().replace('\\n', '\n')
print(line)
The .rstrip()
removes the trailing whitespaces, including the binary form of \n
. The .replace()
causes explicit, user defined interpretation of your \n
sequences in the file content -- captured as the printable character \
followed by the n
.
When using the with
construct, the f.close()
is done automatically.
Upvotes: 0
Reputation: 142106
Sorry - this isn't valid for Python 3.x (I was looking at the tags), but I'll leave here as reference - please see @Ignacio's answer: https://stackoverflow.com/a/14193673/1252759
If you've effectively got a raw string
that contains the literal characters '\n'
, then you can re-interpret the string to make it an escape sequence again:
>>> a = r"Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM"
>>> print a
Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM
>>> print a.decode('string_escape')
Answers: A, B, and E.
Common components inside a PC include
the CPU,motherboard, and
RAM
You may also want to look at the textwrap
module if you want to wrap lines to a certain width for certain displays...
Upvotes: -1
Reputation: 798456
You don't have "\n"
in the string, you have "\\n"
since you're reading it from a file. If you want to have "\n"
then you need to decode the string. Note that 3.x doesn't have str.decode()
, so you can't use that mechanism from 2.x.
3>> codecs.getdecoder('unicode-escape')('foo\\nbar')[0]
'foo\nbar'
Upvotes: 4