Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'str' object has no attribute 'decode'

I'm trying to decode hex string to binary values. I found this below command on internet to get it done,

string_bin = string_1.decode('hex')

but I got error saying

'str' object has no attrubute 'decode'

I'm using python v3.4.1

like image 394
rao Avatar asked Mar 13 '15 11:03

rao


People also ask

How to fix str object has no attribute decode?

Conclusion # The Python "AttributeError: 'str' object has no attribute 'decode'" occurs when we call the decode() method on a string that has already been decoded from bytes. To solve the error, remove the call to the decode() method as the string is already decoded.

How do you decode a string in Python?

decode() is a method specified in Strings in Python 2. This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string.


2 Answers

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.

like image 85
Martijn Pieters Avatar answered Sep 27 '22 17:09

Martijn Pieters


Use binascii:

import binascii

binary_string = binascii.unhexlify(hex_string)
like image 40
orlp Avatar answered Sep 27 '22 17:09

orlp