python2 'str' object has no attribute 'decode'


'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')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM