Python 打印“\n”或换行符作为终端输出的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31624041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:19:13  来源:igfitidea点击:

Print "\n" or newline characters as part of the output on terminal

pythonstringnewline

提问by wolfgang

I'm running Python on terminal

我在终端上运行 Python

Given a string string = "abcd\n"

给定一个字符串 string = "abcd\n"

I'd like to printit somehow so that the newline characters '\n'in abcd\nwould be visible rather than go to the next line

我想print它在某种程度上,这样的换行符'\n'abcd\n将是可见的,而不是去到下一行

Can I do this without having to modify the string and adding a double slash (\\n)

我可以这样做而不必修改字符串并添加双斜杠 ( \\n)

采纳答案by Bhargav Rao

Use repr

repr

>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'

回答by Michel85

If you're in control of the string, you could also use a 'Raw' string type:

如果您可以控制字符串,还可以使用“原始”字符串类型:

>>> string = r"abcd\n"
>>> print(string)
abcd\n

回答by Gildas

Another suggestion is to do that way:

另一个建议是这样做:

string = "abcd\n"
print(string.replace("\n","\n"))

But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n

但请注意,打印功能实际上将“\n”打印到终端,您的终端将其解释为换行符,仅此而已。所以,我的解决方案只是更改 \ + n 中的换行符