[英]In Python, is it possible to escape newline characters when printing a string?
I want the newline \\n
to show up explicitly when printing a string retrieved from elsewhere. 我希望换行
\\n
在打印从其他位置检索的字符串时显式显示。 So if the string is 'abc\\ndef' I don't want this to happen: 因此,如果字符串为“ 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? 有没有一种方法可以修改打印,或修改参数,或者完全修改另一个函数来完成此任务?
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
. 在python3中,
'string_escape'
已成为unicode_escape
。 Additionally, we need to be a little more careful about bytes/unicode so it involves a decoding after the encoding: 此外,我们需要对字节/ unicode更加谨慎,因此它涉及编码后的解码:
>>> print("foo\nbar".encode("unicode_escape").decode("utf-8"))
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 使用
repr()
的唯一问题是它将字符串放在单引号中,如果您想使用引号会很方便
Simplest method: str_object.replace("\\n", "\\\\n")
最简单的方法:
str_object.replace("\\n", "\\\\n")
The other methods are better if you want to show all escape characters, but if all you care about is newlines, just use a direct replace. 如果要显示所有转义字符,则其他方法更好,但是如果您只关心换行符,则只需使用直接替换即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.