属性错误:'str'对象没有'decode'属性 Python3

5 投票
1 回答
20071 浏览
提问于 2025-04-18 02:30

这一行代码在 Python 2.7.6 中运行得很好,但在 Python 3.3.5 中就出错了。我该如何在 Python 3 中将其解码为 hex 值呢?

return x.replace(' ', '').replace('\n', '').decode('hex')

错误追踪信息

AttributeError: 'str' object has no attribute 'decode'

1 个回答

2

要把十六进制转换成字符串,可以使用 binascii.unhexlify

>>> from binascii import unhexlify
>>> unhexlify(x.replace(' ', '').replace('\n', ''))

不过,在 Python 3 中,你首先需要把 x 转换成 bytes,这样才能正常工作。你可以这样做:

>>> x = x.encode('ascii', 'strict')

然后就可以进行十六进制到字符串的转换了。

撰写回答