【问题标题】:Unable to decode bytearray in python 3 but possible in python 2无法在 python 3 中解码字节数组,但在 python 2 中可能
【发布时间】: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


【解决方案1】:

ascii 是 7 位的。使用iso-8859-15 或类似的8 位。您选择哪一种 8 位编解码器取决于您首选的高位字符映射。

>>> print(bytearray(b"\x0e6G\xe8Y-5QJ\x08\x12CX%6\xed=\xe6s@Y\x00\x1e?S\\\xe6\'\x102").decode("iso-8859-15"))
6GèY-5QCX%6í=æs@Y?S\æ'2
>>> print(bytearray(b"\x0e6G\xe8Y-5QJ\x08\x12CX%6\xed=\xe6s@Y\x00\x1e?S\\\xe6\'\x102").decode("iso-8859-15").encode("iso-8859-15") == bytearray(b"\x0e6G\xe8Y-5QJ\x08\x12CX%6\xed=\xe6s@Y\x00\x1e?S\\\xe6\'\x102"))
True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2011-12-13
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多