字符串中的“\n”不起作用

"\n" in strings not working

我有一小段适用于我的操作系统的代码:

print("Type your document below.")
print("Press enter to save.")
print("Type \n for a new line.")
file=input()
print("Enter a file name...")
filename=input()
outFile = open(filename, "w+")
outFile.write(file)
outFile.close()

但是当我 运行 这段代码(在 def 中)时,假设我输入了这样的内容:

foo \n bar

因为在接收用户输入时输入不起作用,所以你必须使用\n。

文件结果为:

foo \n bar

而不是:

foo
bar

\n 是转义序列,仅适用于 字符串文字 input() 不采用字符串文字,它采用用户输入的文本并且不对其进行任何处理,因此输入 \ 后跟 n 的任何人都会生成一个包含两个字符的字符串,反斜杠和字母 n,而不是换行符。

您必须自己处理此类转义:

file = file.replace(r'\n', '\n')

这里我使用了一个原始字符串文字,它也不支持转义序列,来定义文字反斜杠 \ 后跟 n.

或者,反复询问用户新的文件名,直到他们完成:

lines = []
print('Type in your document, followed by a blank line:')
while True:
    line = input("> ")
    if not line:
        break
    lines.append(line)
file = '\n'.join(lines)

演示:

>>> lines = []
>>> print('Type in your document, followed by a blank line:')
Type in your document, followed by a blank line:
>>> while True:
...     line = input("> ")
...     if not line:
...         break
...     lines.append(line)
...
> foo
> bar
>
>>> lines
['foo', 'bar']
>>> '\n'.join(lines)
'foo\nbar'

正如 Martijn 所解释的,您需要自己处理替换。最简单的方法就是直接使用 .replace 方法:

>>> print(input('Enter \n for newline: ').replace('\n', '\n'))
Enter \n for newline: This is my \nnewline
This is my 
newline

这适用于 \n 转义序列,但如果您需要其他转义序列(例如 \t),则需要自己实现。

请注意,如果你想支持 Python 风格的字符串(不仅有 \n,还有 \t\r\u1234 等.),您应该将 codecs.decodeunicode_escape 处理程序一起使用:

contents = input()
contents = codecs.decode(contents, "unicode_escape")

请注意,这将会改变

foo\nbar\nbash\u1234

foo
bar\nbashሴ

您还需要处理错误。您可以通过捕获 UnicodeDecodeError 或使用错误替换策略来执行此操作:

contents = input()
contents = codecs.decode(contents, "unicode_escape", errors="replace")

遗憾的是,这似乎与 unicode 字符混淆:

codecs.decode("α", "unicode_escape")
#>>> 'α'

我知道的最简单的解决方法是先用 raw_unicode_escape:

转义
contents = input()
contents = contents.encode("raw_unicode_escape")
contents = contents.decode("unicode_escape")

这可能比您需要的复杂得多,所以我建议您不要实际这样做。