试图使用decode()方法时出现属性错误。

问题描述 投票:0回答:1

我正在使用一个在python 2.7中运行正常的程序,但当我用python 3运行它时却出现了错误。该程序是解码字符串与蓝牙通信。

代码部分是

senddata = ""
for byte in data:
    byte = str(byte)
    senddata += byte.decode ("hex")
self.controlsocket.send(senddata)

我得到了下面的错误信息

AttributeError: 'str' object has no attribute 'decode' 
python python-3.x raspberry-pi decoding
1个回答
2
投票

在Python 3中删除了文本到文本和二进制到二进制的编码(不是完全删除,但使用起来比较困难),在这里 str 仅有 encode (从文本转换为二进制)和 bytes 仅有 decode (从二进制转换为文本)。

要将十六进制字符串转换为原始底层字节,你可以使用 binascii.unhexlify (可在2& 3之间移植,但需要导入)或 bytes.fromhex (仅在现代 Python 3 上可用,但不需要导入)。

可以 中的函数,仍然使用原始的二进制到二进制编解码器。codecs 模块,但通常不值得这么麻烦;他们在这个模块中给出了更好的等价物。codecs 文件.

© www.soinside.com 2019 - 2024. All rights reserved.