给定两个几乎相同的文本文件(纯文本,在 MacVim 中创建),将它们读入 Python 中的变量时会得到不同的结果。我想知道为什么会这样以及如何产生一致的行为。
例如,f1.txt 如下所示:
This isn't a great example, but it works.
f2.txt 看起来像这样:
This isn't a great example, but it wasn't meant to be.
"But doesn't it demonstrate the problem?," she said.
当我读入这些文件时,使用如下内容:
f = open("f1.txt","r")
x = f.read()
当我查看控制台中的变量时,我得到以下信息。f1.txt:
>>> x
"This isn't a great example, but it works.\n\n"
和 f2.txt:
>>> y
'This isn\'t a great example, but it wasn\'t meant to be. \n"But doesn\'t it demonstrate the problem?," she said.\n\n'
换句话说, f1 只带有转义的换行符,而 f2 的单引号也被转义了。
repr() 显示发生了什么。首先是 f1:
>>> repr(x)
'"This isn\'t a great example, but it works.\\n\\n"'
f2:
>>> repr(y)
'\'This isn\\\'t a great example, but it wasn\\\'t meant to be. \\n"But doesn\\\'t it demonstrate the problem?," she said.\\n\\n\''
这种行为快把我逼疯了。发生了什么事,我如何使它保持一致?如果这很重要,我会尝试以纯文本形式阅读,对其进行操作,并最终将其写出,以便显示正确转义的字符(用于粘贴到 Javascript 代码中)。