Python 3 字符串转16进制
在Python 2中,这些代码都能正常运行:
>>> "hello".encode("hex")
'68656c6c6f'
>>> b"hello".encode("hex")
'68656c6c6f'
>>> u"hello".encode("hex")
'68656c6c6f'
但是在Python 3中:
>>> "hello".encode("hex")
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
怎么在Python 3中把字符串转换成十六进制呢?
10 个回答
55
在Python 3.5及以上版本中,可以把字符串转换成字节,然后使用hex()
这个方法,这样就会返回一个字符串。
s = "hello".encode("utf-8").hex()
s
# '68656c6c6f'
如果需要的话,还可以把这个字符串再转换回字节:
b = bytes(s, "utf-8")
b
# b'68656c6c6f'
107
在Python 3.x版本中,hex
这个编码方式被去掉了。你可以使用binascii
来代替它:
>>> binascii.hexlify(b'hello')
b'68656c6c6f'