【发布时间】:2022-04-25 13:34:03
【问题描述】:
如何在 Python 3 中打印没有 b' 前缀的 bytes 字符串?
>>> print(b'hello')
b'hello'
【问题讨论】:
标签: python string python-3.x
如何在 Python 3 中打印没有 b' 前缀的 bytes 字符串?
>>> print(b'hello')
b'hello'
【问题讨论】:
标签: python string python-3.x
使用decode:
>>> print(b'hello'.decode())
hello
【讨论】:
utf-8是不是很糟糕?我不想每次打印东西时都使用.decode('utf-8')。
curses.version 不是 None
如果字节已经使用了适当的字符编码;您可以直接打印它们:
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"7"))
b'1337'
>>> print(str(hexlify(b"7"), "utf-8"))
1337
>>> from codecs import encode # alternative
>>> print(str(encode(b"7", "hex"), "utf-8"))
1337
【讨论】:
根据bytes.__repr__ 的来源,b'' 被烘焙到方法中。
一种解决方法是从生成的repr() 中手动切掉b'':
>>> x = b''
>>> print(repr(x))
b''
>>> print(repr(x)[2:-1])
【讨论】:
repr(x)[2:-1],会生成一个str 对象,该对象将如愿打印。特别是,repr(b'')[2:-1] 返回字符串\x01,而decode() 将返回,这与print() 不同。更明确地说,print(repr(b'')[2:-1]) 将打印 而print(b''.decode()) 不会打印任何内容。
print(repr(b"".decode())) 将打印 ''(包含单引号的字符串),以便 print(repr(b"".decode())[1:-1]) 打印 (不包含单引号的字符串)。
显示或打印:
<byte_object>.decode("utf-8")
编码或保存:
<str_object>.encode('utf-8')
【讨论】:
我有点晚了,但是对于 Python 3.9.1,这对我有用并删除了 -b 前缀:
print(outputCode.decode())
【讨论】:
就是这么简单... (这样,您可以对字典和列表字节进行编码,然后可以使用 json.dump / json.dumps 对其进行字符串化)
你只需要使用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
【讨论】: