AttributeError:'str'对象没有属性'decode'在我代码的第二行出现此错误

时间:2018-07-23 12:34:48

标签: python algorithm encryption

这是我的代码,

if __name__ == "__main__":
    key = "0123456789abcdef0123456789abcdef".decode('hex')  /this line is having error
    plain_1 = "1weqweqd"
    plain_2 = "23444444"
    plain_3 = "dddd2225"
    print(plain_1)
    print(plain_2)
    print(plain_3)

    cipher = Present(key)

输出

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

1 个答案:

答案 0 :(得分:1)

这是因为您尝试解码字符串。 bytes类型可以被解码,但是str类型不能被解码。您应该对此进行编码(key.encode()(或使用b"foo"),才能将字符串转换为bytes对象。

>>> foo = "adarcfdzer"
>>> type(foo)
<class 'str'>
>>> foo = foo.encode()
>>> type(foo)
<class 'bytes'>
>>> foo = foo.decode()
>>> type(foo)
<class 'str'>