python 3.2.3忽略字符串中的转义序列

2024-05-13 12:04:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我正在使用这里找到的一个示例从文件中读取行并打印它们。我不明白的是为什么解释器忽略了\n转义序列:

文本文件:

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

Python代码:

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()

我得到的结果是字符串如下:

Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM

我只是在寻找一种简单的方式格式化长行以适应屏幕。


Tags: andforincludelinecomponentscpufnameanswers
3条回答

尝试以下代码以获得所需的行为。。。

questions_fname = "Test.txt"

with open(questions_fname) as f:
    for line in f:
        line = line.rstrip().replace('\\n', '\n')
        print(line)

.rstrip()删除后面的空白,包括\n的二进制形式。.replace()会导致对文件内容中的\n序列的显式、用户定义的解释—捕获为可打印字符\,后跟n

当使用with构造时,f.close()将自动完成。

\仅在Python脚本中是转义字符,而不是在文本文件中。当读取文本文件时,Python将所有反斜杠转换为\\,因此当读取文件时,\n变为\\n,而不是换行符

字符串中没有"\n",从文件中读取后就有"\\n"。如果你想拥有"\n",那么你需要解码这个字符串。注意3.x没有str.decode(),因此不能从2.x使用该机制

3>> codecs.getdecoder('unicode-escape')('foo\\nbar')[0]
'foo\nbar'

相关问题 更多 >