"\ n"在字符串不起作用 [英] "\n" in strings not working
本文介绍了"\ n"在字符串不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于我的操作系统,我有这小段代码:
I have this little piece of code for my sort of Operating System:
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中)时,说我输入了这样的内容:
but when I run this code (which is in a def), say I enter something like this:
foo \n bar
由于在接收用户输入时输入不起作用,因此您必须使用\ n.
because enters dont work when recieving input from the users, so you have to use \n.
文件显示为:
foo \n bar
代替:
foo
bar
推荐答案
正如Martijn所说,您需要自己处理替换项.最简单的方法是使用.replace
方法:
As Martijn explained you'll need to process the replacements yourself. The easiest way to do that is literally with the .replace
method:
>>> print(input('Enter \\n for newline: ').replace('\\n', '\n'))
Enter \n for newline: This is my \nnewline
This is my
newline
这对于\n
转义序列可以很好地工作,但是如果您想要其他人(例如\t
),则需要自己实现.
This will work fine for the \n
escape sequence, but if you want others (e.g. \t
) then you'll need to implement that yourself.
这篇关于"\ n"在字符串不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文