在Python 3中禁止/打印没有b'前缀的字节

时间:2013-05-25 09:14:04

标签: python string python-3.x

只是张贴这个,以便我可以在以后搜索它,因为它似乎总是让我感到困惑:

$ 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'"

问题:如何在Python 3中打印二进制(bytes)字符串,而没有b'前缀?

6 个答案:

答案 0 :(得分:78)

使用decode

>>> print(curses.version.decode('utf-8'))
2.2

答案 1 :(得分:16)

如果字节已经使用了适当的字符编码;你可以直接打印出来:

sys.stdout.buffer.write(data)

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

答案 2 :(得分:6)

如果数据采用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

答案 3 :(得分:3)

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

print(outputCode.decode())

答案 4 :(得分:2)

您可以使用以下代码进行显示或打印:

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

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

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

答案 5 :(得分:0)

如果我们查看bytes.__repr__的来源,就好像b''被烘焙到方法中一样。

最明显的解决方法是从产生的b''中手动切出repr()

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

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

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