ITPub博客

首页 > > > python2 'str' object has no attribute 'decode'

python2 'str' object has no attribute 'decode'

作者:longmanma 时间:2020-01-10 17:51:50 0 删除 编辑
'0102030405060708'.decode('hex')

上述代码,报错:

'str' object has no attribute 'decode'

查找原因:

https://stackoverflow.com/questions/29030725/str-object-has-no-attribute-decode

You cannot decode string objects; they are already decoded. You'll have to use a different method.

You can use the codecs.decode() function to apply hex as a codec:

>>> import codecs
>>> codecs.decode('ab', 'hex')
b'\xab'

This applies a Binary transform codec; it is the equivalent of using the base64.b16decode() function, with the input string converted to uppercase:

>>> import base64
>>> base64.b16decode('AB')
b'\xab'

You can also use the binascii.unhexlify() function to 'decode' a sequence of hex digits to bytes:

>>> import binascii
>>> binascii.unhexlify('ab')
b'\xab'

Either way, you'll get a bytes object.

 

使用第二种方式解决了:

>>> import base64
>>> base64.b16decode('AB')

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2730/viewspace-3118796/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-12-18

  • 博文量
    492
  • 访问量
    12009