python - Python 2.7 与 3.6 中 struct.unpack 的行为差异

标签 python python-3.x python-2.7

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

相关文章:

python - 通过替换对 2D numpy 数组中的行进行采样

python-3.x - 如何通过 Pandas 导入.data并描述数据?

linux - python3 PyQt/PySide Linux 安装

python - 在 Windows 上使用 IDLE 安装 python 模块/包

python - 插入排序不排序

python - 在 Plone 中的字段上移动不变验证错误消息

python - 正则表达式捕获除了一个词以外的所有内容(打破一个词而不是字符)

python - 使用 Python 3 对文件进行 Xor 加密/解密

python - 无法连接到 FTP 服务器

Python to json 将键与成员名称而不是属性名称放在一起