gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:17:03 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com