在 Python 中,打印字符串时是否可以转义换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15392730/
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
In Python, is it possible to escape newline characters when printing a string?
提问by Tyler
I want the newline \nto show up explicitly when printing a string retrieved from elsewhere. So if the string is 'abc\ndef' I don't want this to happen:
我希望\n在打印从其他地方检索的字符串时显式显示换行符。所以如果字符串是 'abc\ndef' 我不希望这种情况发生:
>>> print(line)
abc
def
but instead this:
而是这个:
>>> print(line)
abc\ndef
Is there a way to modify print, or modify the argument, or maybe another function entirely, to accomplish this?
有没有办法修改打印,或修改参数,或者完全是另一个函数来完成这个?
采纳答案by PurityLake
Another way that you can stop python using escape characters is to use a raw string like this:
使用转义字符停止 python 的另一种方法是使用这样的原始字符串:
>>> print(r"abc\ndef")
abc\ndef
or
或者
>>> string = "abc\ndef"
>>> print (repr(string))
>>> 'abc\ndef'
the only proplem with using repr()is that it puts your string in single quotes, it can be handy if you want to use a quote
using 的唯一问题repr()是它将您的字符串放在单引号中,如果您想使用引号,它会很方便
回答by mgilson
Just encode it with the 'string_escape'codec.
只需使用'string_escape'编解码器对其进行编码即可。
>>> print "foo\nbar".encode('string_escape')
foo\nbar
In python3, 'string_escape'has become unicode_escape. Additionally, we need to be a little more careful about bytes/unicode so it involves a decoding after the encoding:
在python3中,'string_escape'已经成为unicode_escape. 此外,我们需要对字节/unicode 更加小心,因此它涉及编码后的解码:
>>> print("foo\nbar".encode("unicode_escape").decode("utf-8"))
回答by ACEfanatic02
Simplest method:
str_object.replace("\n", "\\n")
最简单的方法:
str_object.replace("\n", "\\n")
The other methods are better if you want to show allescape characters, but if all you care about is newlines, just use a direct replace.
如果您想显示所有转义字符,其他方法会更好,但如果您只关心换行符,只需使用直接替换。

