Converting from hexadecimal string to unicode

How can I convert a string 'dead'

to a unicode string u'\xde\xad'

?

Doing this action:

from binascii import unhexlify
out = ''.join(x for x in [unhexlify('de'), unhexlify('ad')])

      

creates a string <type 'str'>

'\xde\xad'

Trying to use Unicode.join () like this:

from binascii import unhexlify
out = ''.join(x for x in [u'', unhexlify('de'), unhexlify('ad')])

      

results in an error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xde in position 0: ordinal not in range(128)

      

+2


source to share


2 answers


Unicode is designed to be Latin-1 compatible, you can use it and just decode bytestring:



In [2]: unhexlify('dead').decode('latin1')
Out[2]: u'\xde\xad'

      

+5


source


See this way of using Python unicode and use something similar to:

unicode('\x80abc', errors='replace')

      



or

unicode('\x80abc', errors='ignore')

      

+1


source







All Articles