【问题标题】:AttributeError: 'str' object has no attribute 'decode' Having this error on the second line of my codeAttributeError: 'str' object has no attribute 'decode' 在我的代码的第二行出现此错误
【发布时间】:2018-07-23 20:54:32
【问题描述】:

这是我的代码,

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'

【问题讨论】:

  • str 在 Python 2 中有 decode 方法,但在 Python 3 中没有。
  • 使用:binascii.unhexlify('0123456789abcdef0123456789abcdef')
  • 这里有人遇到过类似问题:stackoverflow.com/questions/3283984/…
  • 你想解码十六进制数字并且你试图解码字符串我认为这可能是问题。

标签: python algorithm encryption


【解决方案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'>

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 2021-06-05
    • 1970-01-01
    • 2020-04-26
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多