2024-04-29 03:12:13 发布
网友
我希望在打印从其他地方检索到的字符串时,新行\n显式显示。所以如果字符串是'abc\ndef',我不希望发生这种情况:
\n
>>> print(line) abc def
但事实上:
>>> print(line) abc\ndef
有没有办法修改print,或者修改参数,或者完全修改另一个函数来完成这个任务?
另一种阻止python使用转义字符的方法是使用如下原始字符串:
>>> print(r"abc\ndef") abc\ndef
或者
>>> string = "abc\ndef" >>> print (repr(string)) >>> 'abc\ndef'
使用repr()的唯一问题是它将字符串放在单引号中,如果您想使用引号,它会很方便
repr()
最简单的方法: str_object.replace("\n", "\\n")
str_object.replace("\n", "\\n")
如果您想显示all转义字符,其他方法更好,但是如果您只关心换行符,只需使用直接替换。
只需使用'string_escape'编解码器对其进行编码。
'string_escape'
>>> print "foo\nbar".encode('string_escape') foo\nbar
在Python3中,'string_escape'变成了unicode_escape。另外,我们需要对bytes/unicode更加小心一些,这样就需要在编码之后进行解码:
unicode_escape
>>> print("foo\nbar".encode("unicode_escape").decode("utf-8"))
unicode_escape reference
另一种阻止python使用转义字符的方法是使用如下原始字符串:
或者
使用
repr()
的唯一问题是它将字符串放在单引号中,如果您想使用引号,它会很方便最简单的方法:
str_object.replace("\n", "\\n")
如果您想显示all转义字符,其他方法更好,但是如果您只关心换行符,只需使用直接替换。
只需使用
'string_escape'
编解码器对其进行编码。在Python3中,
'string_escape'
变成了unicode_escape
。另外,我们需要对bytes/unicode更加小心一些,这样就需要在编码之后进行解码:unicode_escape reference
相关问题 更多 >
编程相关推荐