如何修复 AttributeError: 'bytes' object has no attribute 'encode'?

cri*_*ker 6 python

这是我的代码z = (priv.to_string().encode('hex')) ,我收到此错误:

"AttributeError: 'bytes' object has no attribute 'encode'"
Run Code Online (Sandbox Code Playgroud)

看起来我错过了在代码后显示“编码”的内容:

z = (priv.to_string().

glh*_*lhr 10

这里有两个问题:

  • 您正在使用priv.to_string()(这不是内置方法)而不是str(priv)
  • 'hex'已作为 Python 3 中的编码删除,因此str(priv).encode('hex')您将收到以下错误:LookupError: 'hex' is not a text encoding; use codecs.encode()to handle arbitrary codecs

但是,从 Python 3.5 开始,您可以简单地执行以下操作:

priv.hex()
Run Code Online (Sandbox Code Playgroud)

priv作为一个字节的字符串。

例子:

priv = b'test'
print(priv.hex())
Run Code Online (Sandbox Code Playgroud)

输出:

74657374
Run Code Online (Sandbox Code Playgroud)