The Python Oracle

Convert from ASCII string encoded in Hex to plain ASCII?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind

--

Chapters
00:00 Convert From Ascii String Encoded In Hex To Plain Ascii?
00:19 Answer 1 Score 50
00:46 Accepted Answer Score 260
00:57 Answer 3 Score 185
01:07 Answer 4 Score 46
01:18 Thank you

--

Full question
https://stackoverflow.com/questions/9641...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #hex #ascii

#avk47



ACCEPTED ANSWER

Score 260


A slightly simpler solution (python 2 only):

>>> "7061756c".decode("hex")
'paul'



ANSWER 2

Score 185


No need to import any library:

>>> bytearray.fromhex("7061756c").decode()
'paul'



ANSWER 3

Score 50


>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'                                                                          

i'm just having fun, but the important parts are:

>>> int('0a',16)         # parse hex
10
>>> ''.join(['a', 'b'])  # join characters
'ab'
>>> 'abcd'[0::2]         # alternates
'ac'
>>> zip('abc', '123')    # pair up
[('a', '1'), ('b', '2'), ('c', '3')]        
>>> chr(32)              # ascii to character
' '

will look at binascii now...

>>> print binascii.unhexlify('7061756c')
paul

cool (and i have no idea why other people want to make you jump through hoops before they'll help).




ANSWER 4

Score 46


In Python 2:

>>> "7061756c".decode("hex")
'paul'

In Python 3:

>>> bytes.fromhex('7061756c').decode('utf-8')
'paul'