我的操作系统有一小段代码:
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
答案 0 :(得分:8)
\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'
答案 1 :(得分:4)
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
),那么您需要自己实现。
答案 2 :(得分:2)
请注意,如果您想支持Python风格的字符串(不仅包括input_name
,还包括from django.core.exceptions import ValidationError
def validate_input_name(value):
if value == 'MyKeyword':
raise ValidationError("The model already exists")
,\n
,\t
等),您应该使用\r
使用\u1234
处理程序:
codecs.decode
请注意,这将改变
unicode_escape
到
contents = input()
contents = codecs.decode(contents, "unicode_escape")
您还需要处理错误。您可以通过捕获foo\nbar\\nbash\u1234
或使用错误替换策略来执行此操作:
foo
bar\nbashሴ
可悲的是,这似乎搞乱了unicode角色:
UnicodeDecodeError
我所知道的最简单的解决方法是首先使用contents = input()
contents = codecs.decode(contents, "unicode_escape", errors="replace")
转义:
codecs.decode("α", "unicode_escape")
#>>> 'α'
这可能比您需要的要复杂得多,所以我建议不要这样做。