我正在将代码库从 Python 2.7 转换为 Python 3.6。我有这个代码:
import struct
unpacked = struct.unpack('<BI6s', '\x02\xff\x01\x00\x00tester', offset=0)
在Python 2.7中,unpacked = (2, 511, 'tester')
,这就是我想要的。
在Python 3.6中,由于struct.unpack
期望第二个参数是bytes
,所以我尝试了以下操作:
import struct
unpacked = struct.unpack('<BI6s', bytes('\x02\xff\x01\x00\x00tester', 'utf8'), offset=0)
并且解压 = (2, 114627, b'\x00teste')
。
为什么我会得到不同的结果?如何才能得到与 2.7 中相同的结果?
最佳答案
问题出在 bytes()
调用上:
>>> bytes('\x02\xff\x01\x00\x00tester', 'utf8')
b'\x02\xc3\xbf\x01\x00\x00tester'
看到多余的字节\xc3\xbf
吗? Python 3 字符串是 unicode,字符串中第二个字符 (U+00FF
) 的 UTF-8 编码是 0xC3 0xBF(请参阅 https://www.compart.com/en/unicode/U+00FF )。
解决方案是使用字节文字,其行为与 Python 2 相同:
unpacked = struct.unpack('<BI6s', b'\x02\xff\x01\x00\x00tester', offset=0)
关于python - Python 2.7 与 3.6 中 struct.unpack 的行为差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59606648/