在Python 3中将字节转换为十六进制字符串的正确方法是什么? [英] What's the correct way to convert bytes to a hex string in Python 3?

查看:106
本文介绍了在Python 3中将字节转换为十六进制字符串的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3中将字节转换为十六进制字符串的正确方法是什么?



我看到 bytes.hex 方法, bytes.decode 编解码器,并尝试其他可能的最不惊人的功能无效。我只想把我的字节当作十六进制!

解决方案使用 binascii 模块:

 >>> import binascii 
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_)。decode('utf8')
'foo'

请参阅这个答案:
Python 3.1.1字符串到十六进制


What's the correct way to convert bytes to a hex string in Python 3?

I see claims of a bytes.hex method, bytes.decode codecs, and have tried other possible functions of least astonishment without avail. I just want my bytes as hex!

解决方案

Use the binascii module:

>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'

See this answer: Python 3.1.1 string to hex

这篇关于在Python 3中将字节转换为十六进制字符串的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆