在Python中,是否可以在打印字符串时转义换行符?

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)

unicode_escape参考

  • Python 3中的等价物就像"foo \nbar".encode('utf8').decode('unicode_escape')`. (3认同)
  • `.encode('string_escape')的语义是否记录在任何地方? (3认同)
  • 如果字符串来自DOM对象,可能需要使用'unicode-escape'而不是'string_escape' (2认同)

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")

如果要显示所有转义字符,其他方法会更好,但如果您关心的只是换行符,则只需使用直接替换.

  • 不不不!Python 2.7和Python 3之间没有区别。按照答案说。`replace(r“ \ n”,r“ \\ n”)`是没有用的,它不会碰到换行符。 (3认同)