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

时间:2013-03-13 17:49:00

标签: python escaping newline

我希望在打印从其他地方检索到的字符串时显式显示换行符\n。因此,如果字符串是'abc \ ndef',我不希望发生这种情况:

>>> print(line)
abc
def

但改为:

>>> print(line)
abc\ndef

有没有办法修改print,或者修改参数,或者完全修改另一个函数来实现这个目的?

3 个答案:

答案 0 :(得分:77)

只需使用'string_escape'编解码器对其进行编码。

>>> print "foo\nbar".encode('string_escape')
foo\nbar

在python3中,'string_escape'已成为unicode_escape。另外,我们需要对字节/ unicode更加小心,因此它涉及编码后的解码:

>>> print("foo\nbar".encode("unicode_escape").decode("utf-8"))

unicode_escape reference

答案 1 :(得分:50)

使用转义字符停止python的另一种方法是使用这样的原始字符串:

>>> print(r"abc\ndef")
abc\ndef

>>> string = "abc\ndef"
>>> print (repr(string))
>>> 'abc\ndef'

使用repr()的唯一问题是,它将您的字符串放在单引号中,如果您想使用引号,它可以很方便

答案 2 :(得分:18)

最简单的方法: str_object.replace("\n", "\\n")

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