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

9

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

在旧版本的Python中,我下面的代码可以工作:

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

但是在使用Python3时,我遇到了以下错误:

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

有人可以告诉我在Python3中该如何转换吗?

谢谢!

3个回答

10

在Python 3.x中,使用binascii代替hex:

>>> import binascii
>>> binascii.hexlify(b'< character / string>')

4

打印:

for c in test:
    print(hex(ord(c)))

为了转换:
output = ''.join(hex(ord(c)) for c in test)

或者输出时不包含'0x':

output = ''.join(hex(ord(c))[2:] for c in test)

1
怎么样:
>>> test = "This is a test"    
>>> for c in range(0, len(test) ):
...     print( "0x%x"%ord(test[c]))
... 
0x54
0x68
0x69
0x73
0x20
0x69
0x73
0x20
0x61
0x20
0x74
0x65
0x73
0x74

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接