理解python 2.7和3.5+中的struct.pack

Sam*_*amy 4 struct python-2.7 python-3.x

我试图理解;并解决,为什么会发生以下情况:

$ python
>>> import struct
>>> list(struct.pack('hh', *(50,50)))
['2', '\x00', '2', '\x00']
>>> exit()
$ python3
>>> import struct
>>> list(struct.pack('hh', *(50, 50)))
[50, 0, 50, 0]
Run Code Online (Sandbox Code Playgroud)

我知道这hh代表 2 条短裤。我知道这struct.pack是将两个整数(shorts)转换为c style struct. 但是为什么 2.7 中的输出与 3.5 有如此大的不同呢?

不幸的是,我python 2.7现在在这个项目上被困住了,我需要输出类似于来自python 3.5

回应 Some Programmer Dude 的评论

$ python
>>> import struct
>>> a = list(struct.pack('hh', *(50, 50)))
>>> [int(_) for _ in a]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 6

在python 2中,struct.pack('hh', *(50,50))返回一个str对象。

这在python 3中发生了变化,它返回一个bytes对象(二进制和字符串之间的区别是两个版本之间非常重要的区别,即使bytes存在于python 2中,它也与 相同str)。

要在 python 2 中模拟这种行为,您可以通过ord应用于结果的每个字符来获取字符的 ASCII 代码:

map(ord,struct.pack('hh', *(50,50)))
Run Code Online (Sandbox Code Playgroud)