Python3 - 如何将字符串转换为十六进制

God*_*ped 8 python python-3.x

我正在尝试将字符串逐个字符转换为十六进制字符,但我无法在 Python3 中弄清楚。

在较旧的 python 版本中,我的以下内容有效:

test = "This is a test"
for c in range(0, len(test) ):
   print( "0x%s"%string_value[i].encode("hex") )
Run Code Online (Sandbox Code Playgroud)

但是使用 python3 我收到以下错误:

LookupError: 'hex' 不是文本编码;使用 codecs.encode() 处理任意编解码器。

任何人都可以帮助告诉我 python3.0 中的转换是什么。

提前致谢

Ton*_*ent 10

在 python 3x 中使用binascii而不是十六进制:

>>> import binascii
>>> binascii.hexlify(b'< character / string>')
Run Code Online (Sandbox Code Playgroud)