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

sda*_*aau 88 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'"
Run Code Online (Sandbox Code Playgroud)

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

sda*_*aau 89

用途decode:

print(curses.version.decode())
# 2.2
Run Code Online (Sandbox Code Playgroud)

  • `.decode()`默认也解码'utf-8' (18认同)
  • 请记住,您可以接受自己的答案. (9认同)
  • 默认情况下如何做到这一点,我的意思是,默认使用“utf-8”是否不好?我不想每次打印东西时都使用 `.decode('utf-8')` 。 (3认同)

jfs*_*jfs 17

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

sys.stdout.buffer.write(data)
Run Code Online (Sandbox Code Playgroud)

要么

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


Mat*_*haq 14

如果我们查看 的源代码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
Run Code Online (Sandbox Code Playgroud)

  • 旁注:我不认为任何其他答案*真正*回答了这个问题。 (8认同)

has*_*.sd 10

显示或打印:

<byte_object>.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)

编码或保存:

<str_object>.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)


Fra*_*ank 6

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

>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2
Run Code Online (Sandbox Code Playgroud)

如果数据尚不兼容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
Run Code Online (Sandbox Code Playgroud)