这是来自 standard library documentation 的函数描述.
binascii.a2b_hex(hexstr)
Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise a TypeError is raised.
但是,下面的代码示例打印出 Hello World!
import binascii
print binascii.a2b_hex('48656c6c6f20576f726c6421')
为什么 print 将二进制数据解释为字符串?到底是怎么回事?
请您参考如下方法:
因为在 Python 2 中,所有二进制数据都表示为字符串。 str 类型基本上只是一个字节序列。
在 Python 3 中,基本的 str 类型是一个 unicode 值(unicode() 在 Python 2 中)和 Python 2 str 类型已重命名为 bytes,a2b_hex 函数输出字节:
>>> import binascii
>>> binascii.a2b_hex('48656c6c6f20576f726c6421')
b'Hello World!'
