Tyl*_*ler 52 python newline escaping
我希望\n在打印从其他地方检索的字符串时显式显示换行符.因此,如果字符串是'abc \ndef',我不希望发生这种情况:
>>> print(line)
abc
def
Run Code Online (Sandbox Code Playgroud)
但相反:
>>> print(line)
abc\ndef
Run Code Online (Sandbox Code Playgroud)
有没有办法修改打印,或修改参数,或完全是另一个功能,来实现这一目标?
mgi*_*son 81
只需用'string_escape'编解码器对其进行编码即可.
>>> print "foo\nbar".encode('string_escape')
foo\nbar
Run Code Online (Sandbox Code Playgroud)
在python3中,'string_escape'已经成为unicode_escape.另外,我们需要对字节/ unicode更加小心,因此它涉及编码后的解码:
>>> print("foo\nbar".encode("unicode_escape").decode("utf-8"))
Run Code Online (Sandbox Code Playgroud)
Pur*_*ake 53
另一种可以使用转义字符停止python的方法是使用这样的原始字符串:
>>> print(r"abc\ndef")
abc\ndef
Run Code Online (Sandbox Code Playgroud)
要么
>>> string = "abc\ndef"
>>> print (repr(string))
>>> 'abc\ndef'
Run Code Online (Sandbox Code Playgroud)
使用的唯一问题repr()是它将你的字符串放在单引号中,如果你想使用引号它可以很方便
ACE*_*c02 19
最简单的方法:
str_object.replace("\n", "\\n")
如果要显示所有转义字符,其他方法会更好,但如果您关心的只是换行符,则只需使用直接替换.