Python2转Python3后swap_endian_words函数报TypeError求助
Python 2转3后swap_endian_words函数报错修复
问题原因
Python 3中unhexlify()返回的是bytes对象,而非Python 2中的str类型。你的代码用''.join()拼接反转后的bytes片段,但''.join()要求所有元素都是字符串类型,类型不匹配导致抛出TypeError。
修复方案
推荐使用b''.join()来拼接bytes片段(符合Python 3中二进制数据的处理规范),修改后的代码如下:
from binascii import unhexlify def swap_endian_words(hex_words): '''Swaps the endianness of a hexadecimal string of words and converts to binary bytes.''' message = unhexlify(hex_words) if len(message) % 4 != 0: raise ValueError('Must be 4-byte word aligned') # 用bytes类型的空串拼接bytes片段 return b''.join([message[4 * i: 4 * i + 4][::-1] for i in range(len(message) // 4)]) print(swap_endian_words('aabbccdd')) # 输出结果:b'\xdd\xcc\xbb\xaa'
额外说明
- 如果业务逻辑确实需要返回字符串类型(而非bytes),可以将最终的bytes结果通过
decode()方法转换,但仅当二进制数据可被ASCII编码解析时适用:return b''.join([message[4 * i: 4 * i + 4][::-1] for i in range(len(message) // 4)]).decode('ascii') - Python 2中str和bytes是同一类型,因此原代码可正常运行;Python 3严格区分文本字符串(str)和二进制数据(bytes),必须保证操作的类型一致性。
内容的提问来源于stack exchange,提问作者Sphragistic
相关产品推荐
相关产品推荐

