python2与python3中的decode、encode
python2中尝试将hex字符串转化为字节码常用操作如下
>>> a = 'aabbccddeeff'
>>> a_bytes = a.decode('hex')
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = a_bytes.encode('hex')
>>> print(aa)
aabbccddeeff
但在python3该方法不可行,运行时出现“AttributeError: ‘str’ object has no attribute ‘decode’”错误。原因在于python2中字符串默认编码类型byte,而python3中字符串默认编码类型则是str。
因此在python3中将hex字符串转化为字节码常用操作如下:
>>> a = 'aabbccddeeff'
>>> a_bytes = bytes.fromhex(a)
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = a_bytes.hex()
>>> print(aa)
aabbccddeeff
>>>