python - 字符串中的"\n"无法正常工作

标签 python string python-3.x newline

对于我的操作系统,我有以下这段代码:

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/

相关文章:

c - Strtok 分隔所有空格

python - 打开文本文件,收到编码错误,尝试了多种方法但没有希望

python - 如何减去具有不同填充值的数据框

python - 比 Python 的 find 更强大的方法?正则表达式问题?

python - 刷新装饰器

java - 带空格的字符串赋值返回 null

python-3.x - 用 Pandas 上的值注释条形图(在 Seaborn factorplot 条形图上)

python - 我的程序不会给出成绩

python:将 numpy 数组数据类型从 int64 转换为 int

python - pyqt5 qml 最小示例在退出时崩溃