python - 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 相同的结果?
解决方案
问题在于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)
推荐阅读
- google-apps-script - gmail 插件中的事件或操作
- java - 如何使用 selenium webdriver 在 Safari 中处理地理位置弹出窗口?
- powershell - 通过 Powershell 在线打开 Sharepoint 上的文件并将数据附加到该文件并将其保存回 sharepoint
- memory-leaks - 添加到UIWindow后如何销毁VC?
- python - Pygame 和键盘模块组合,True 循环突然中断
- javascript - 卸载本地软件包时可能导致持续错误的原因是什么?
- mongodb - 找出运行给定 MongoDB 命令所需的权限
- verilog - 如何实现溢出代码?我不知道怎么了
- angular - 自 Angular 8 更新以来,无法导入 Angular 材质的特定入口点
- postgresql - 如何授予对整个数据库的选择权限?(不是模式)