首页 > 解决方案 > 'str' 对象没有属性 'decode' 错误

问题描述

下面的函数首先将十六进制数解码为一个字符串,然后 map 函数将该ord函数应用于所有解码值并给我们一个元组,但是这个解码函数给出了这个错误'str' object has no attribute 'decode'

def hex2rgb(hexcode):
    return tuple(map(ord, hexcode[1:].decode( )))

我正在编写的代码与隐写术有关,这里有一部分代码显示了该函数的输入是如何生成的:

binary = str2bin(message) + '1111111111111110' #converts string into binary and adds the delimeter at end to indicate message is ended

newData = [] #list to store the new pixels which contain the information

img = Image.open(filename)

if img.mode in ('RGBA'):
    img = img.convert('RGBA') #will convert the image into RGBA
    datas = img.getdata()  #will give all the pixel data
    digit = 0 #shows on which binary bit we are currently at      
    for item in datas:
        if (digit < len(binary)):
            newpix = encode(rgb2hex(item[0],item[1],item[2]),binary[digit])
            if newpix == None:
                newData.append(item)
            else:
                r, g, b = hex2rgb(newpix)
                newData.append((r,g,b,255))
                digit += 1

我不明白为什么它不解码。我也试过.decode('hex')or.decode(hex)但它仍然给出错误。

标签: pythonpython-3.xdecode

解决方案


你的方法不正确。因为您正在尝试解码已经解码的字符串。这就是错误来的原因。


推荐阅读