首页 > 解决方案 > Python 2.7 与 3.6 中 struct.unpack 的行为差异

问题描述

我正在将代码库从 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)

unpacked = (2, 114627, b'\x00teste')

为什么我得到不同的结果,我如何得到与 2.7 相同的结果?

标签: pythonpython-3.xpython-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)

推荐阅读