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


112

只需发布此内容,以便稍后查找,因为它总是让我感到困惑:

$ 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'前缀的二进制()字符串?


Answers:


111

用途decode

print(curses.version.decode())
# 2.2

1
@jamylak提醒您它可以接受参数
Jemshit Iskenderov

1
我的意思是默认情况下如何执行此操作默认情况下会不utf-8好吗?我不想.decode('utf-8')每次打印东西时都使用。
Shubham A.

创建自定义打印
SmartManoj

请确保检查是否curses.version为“无”
Cowlinator

24

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

sys.stdout.buffer.write(data)

要么

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

12

如果我们看一下的源代码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

6
旁注:我认为没有其他答案能够真正回答问题。
Mateen Ulhaq '19

我想我会同意:您的解决方案,即repr(x)[2:-1]产生了一个str可以按需打印的对象。特别是,repr(b'\x01')[2:-1]返回字符串\\x01,而decode()将返回\x01却不如预期那样工作print()。更明确地说,print(repr(b'\x01')[2:-1])将在打印\x01print(b'\x01'.decode())不打印任何内容。
Antoine

或者,print(repr(b"\x01".decode()))将打印'\x01'(包含单引号的字符串),以便print(repr(b"\x01".decode())[1:-1])打印\x01(不包含单引号的字符串)。
Antoine

11

如果数据采用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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.