142

只是发布这个,以便我以后可以搜索它,因为它似乎总是让我难过:

$ python3.2
Python 3.2 (r32:88445, Oct 20 2012, 14:09:50) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import curses
>>> print(curses.version)
b'2.2'
>>> print(str(curses.version))
b'2.2'
>>> print(curses.version.encode('utf-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'
>>> print(str(curses.version).encode('utf-8'))
b"b'2.2'"

作为问题:如何bytes在 Python 3 中打印一个没有b'前缀的二进制 ( ) 字符串?

4

8 回答 8

141

使用decode

print(curses.version.decode())
# 2.2
于 2013-05-25T09:14:28.003 回答
27

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

sys.stdout.buffer.write(data)

或者

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes
于 2013-05-25T10:56:52.777 回答
20

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

>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2

如果数据尚未与 UTF-8 兼容,则可选择先转换为十六进制。例如,当数据是实际的原始字节时。

from binascii import hexlify
from codecs import encode  # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337
于 2018-03-19T10:59:01.410 回答
16

如果我们看一下 的源代码bytes.__repr__,它看起来好像是b''被嵌入到方法中的。

b''最明显的解决方法是从结果中手动切掉repr()

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

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

>>> print(repr(x)[2:-1])
\x01\x02\x03\x04
于 2019-07-29T06:41:33.450 回答
8

您可以使用此代码显示或打印:

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

您可以将其用于编码或保存:

<str_object>.encode('utf-8')
于 2020-10-05T20:22:02.223 回答
3

我有点晚了,但是对于 Python 3.9.1,这对我有用并删除了 -b 前缀:

print(outputCode.decode())
于 2021-02-08T19:09:22.140 回答
0

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

>>> import curses
>>> print(curses.version.decode())
2.2
于 2021-12-11T15:09:41.517 回答
0

太简单了......(这样,您可以对字典和列表字节进行编码,然后您可以使用 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())
于 2021-12-11T14:59:16.433 回答