对于我的操作系统,我有以下这段代码:
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
最佳答案
正如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"无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38401450/