我有一小段适合我的操作系统的代码:
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
因为在接收用户输入时 Enter 不起作用,所以您必须使用 \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)
Demo:
>>> 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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)