我正在嘗試bytearray在 Python 3 中將 a 打印為一串 ascii 字符。我有一個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\?'2Python3: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 中相同的行為?print在 Python 2 中,除了簡單地將字節數組解碼為 ascii 之外,還做其他事情嗎?
1 回答

慕運維8079593
TA貢獻1876條經驗 獲得超5個贊
ascii是 7 位。使用iso-8859-158 位等。您選擇哪一種 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
添加回答
舉報
0/150
提交
取消