【发布时间】:2019-09-09 20:51:41
【问题描述】:
我正在尝试将bytearray 打印为 ascii 字符串
Python 3。
我有一个bytearray,我尝试使用 Python 2 和 Python 3 打印它。在 Python 2 中,bytearray 以正确的 ascii 字符打印到控制台。但是,当我在 Python 3 中尝试它时,会出现如下错误:
Python2:
print(bytearray(b"\x0e6G\xe8Y-5QJ\x08\x12CX%6\xed=\xe6s@Y\x00\x1e?S\\\xe6\'\x102"))
# 6G?Y-5QCX%6?=?s@Y?S\?'2
Python3:
print(bytearray(b"\x0e6G\xe8Y-5QJ\x08\x12CX%6\xed=\xe6s@Y\x00\x1e?S\\\xe6\'\x102").decode("ascii"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 3: ordinal not in range(128)
如何在 Python 3 中实现与在 Python 2 中相同的行为? Python 2 中的 print 除了简单地将字节数组解码为 ascii 之外,还做其他事情吗?
【问题讨论】:
-
错误明显在解码中。它永远不会被打印出来。
-
Python 2 可能不使用 ASCII,而是您的终端指定的任何编码(可能是 ISO-8859)。
-
你为什么要包裹在
bytearray?
标签: python arrays encoding python-2to3