在 Python3中打印字节时不使用 b’前缀

在 Python3中,如何在没有 b'前缀的情况下打印 bytes字符串?

>>> print(b'hello')
b'hello'
156706 次浏览

使用 decode:

>>> print(b'hello'.decode())
hello

如果字节已经使用了适当的字符编码,可以直接打印它们:

sys.stdout.buffer.write(data)

或者

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

如果数据采用与 UTF-8兼容的格式,则可以将字节转换为字符串。

>>> print(str(b"hello", "utf-8"))
hello

如果数据不兼容 UTF-8,则可以选择首先转换为十六进制(例如,数据是原始字节)。

>>> from binascii import hexlify
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>> from codecs import encode  # alternative
>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337

根据 bytes.__repr__的源代码,b''被嵌入到方法中。

一种变通方法是手动从产生的 repr()中分离出 b'':

>>> x = b'\x01\x02\x03\x04'


>>> print(repr(x))
b'\x01\x02\x03\x04'


>>> print(repr(x)[2:-1])
\x01\x02\x03\x04

显示或印刷:

<byte_object>.decode("utf-8")

编码或保存:

<str_object>.encode('utf-8')

我有点迟到了,但是对于 Python 3.9.1,这个方法对我很有用,并且去掉了-b 前缀:

print(outputCode.decode())

很简单。 (通过这种方法,可以对字典和列表字节进行编码,然后可以使用 json.dump/json.dump 对其进行字符串化)

你只需要使用 base64

import base64


data = b"Hello world!" # Bytes
data = base64.b64encode(data).decode() # Returns a base64 string, which can be decoded without error.
print(data)

有些字节在默认情况下无法解码(图片就是一个例子) ,所以 base64将把这些字节编码成可以解码为字符串的字节,以检索刚才使用的字节

data = base64.b64decode(data.encode())

使用 decode()而不是 encode()将字节转换为字符串。

>>> import curses
>>> print(curses.version.decode())
2.2