我是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
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
我只是在寻找一种简单的方式格式化长行以适应屏幕。
尝试以下代码以获得所需的行为。。。
.rstrip()
删除后面的空白,包括\n
的二进制形式。.replace()
会导致对文件内容中的\n
序列的显式、用户定义的解释—捕获为可打印字符\
,后跟n
。当使用
with
构造时,f.close()
将自动完成。\
仅在Python脚本中是转义字符,而不是在文本文件中。当读取文本文件时,Python将所有反斜杠转换为\\
,因此当读取文件时,\n
变为\\n
,而不是换行符字符串中没有
"\n"
,从文件中读取后就有"\\n"
。如果你想拥有"\n"
,那么你需要解码这个字符串。注意3.x没有str.decode()
,因此不能从2.x使用该机制相关问题 更多 >
编程相关推荐