字节十六进制对象转换为字符串

Byte hexadecimal object converting to string

我正在将 python 2 代码迁移到 python 3,然后 encode/decode 出现问题。首先,我有多个句子,我应该按以下方式转换:

字符串-->十六进制字符串

之前,在 python 2 中,我使用了类似 hex_message = message.encode("hex") 的代码,然后在迁移之前工作得很好。例如,input->"Hello world", output ->"48656c6c6f20776f726c64"。然后我有这个问题LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs。我将表达式更改为此 hex_message = codecs.encode(message, 'hex'),并且得到此输出 b"48656c6c6f20776f726c64"。所以,没有太多变化,问题是我有一个倍数字符串,它们不是字节对象,我必须加入它们,所以我想编码但不是字节对象,只是字符串。我想像以前一样通过另一个功能或附加功能获得它们。

我找到了解决办法:

message = "Hello world".encode('utf-8') 然后 hex_message = message.hex()。它正在 python3.

工作