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

时间:2022-08-09 20:25:36

I want the newline \n to show up explicitly when printing a string retrieved from elsewhere. 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?

是否有一种方法可以修改打印,或者修改参数,或者完全另一个函数来完成这个?

3 个解决方案

#1


45  

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()的唯一原因是,它将字符串放在单引号中,如果您想使用引号,这将非常方便

#2


70  

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. Additionally, we need to be a little more careful about bytes/unicode so it involves a decoding after the encoding:

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

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

unicode_escape reference

unicode_escape参考

#3


16  

Simplest method: str_object.replace("\n", "\\n")

最简单的方法:str_object。替换(“\ 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.

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

#1


45  

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()的唯一原因是,它将字符串放在单引号中,如果您想使用引号,这将非常方便

#2


70  

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. Additionally, we need to be a little more careful about bytes/unicode so it involves a decoding after the encoding:

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

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

unicode_escape reference

unicode_escape参考

#3


16  

Simplest method: str_object.replace("\n", "\\n")

最简单的方法:str_object。替换(“\ 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.

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