Python Forum

Full Version: convert hex encoded string to ASCII
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
given a string of hexadecimal characters that represent ASCII characters, i want to convert it to those ASCII characters.  for example:

'707974686f6e2d666f72756d2e696f' -> 'python-forum.io'

in python 2 i can do .decode('hex') but this is gone in python3. so, i found this:
codecs.decode(codecs.decode('707974686f6e2d666f72756d2e696f','hex'),'ascii')
anything simpler that works in either python 2 or python 3 ?
How about
codecs.decode("707974686f6e2d666f72756d2e696f", "hex")
Does it give the result you want?
Personally, I've found the fromhex method of bytes to be useful.

print(bytes.fromhex('7370616d'))    # b'spam'
(Sep-29-2016, 07:45 AM)j.crater Wrote: [ -> ]How about
codecs.decode("707974686f6e2d666f72756d2e696f", "hex")
Does it give the result you want?

not in py 3.  i want an ASCII or UTF-8 string, not an array of bytes. this why i added the 2nd call to codecs.decode(,"ascii").
Quote:this why i added the 2nd call to codecs.decode(,"ascii")
You don't need a second call,just add .decode('utf-8').
>>> codecs.decode("707974686f6e2d666f72756d2e696f", "hex").decode('utf-8')
'python-forum.io'
It will work the same in Python 2.x
>>> codecs.decode("707974686f6e2d666f72756d2e696f", "hex").decode('utf-8')
u'python-forum.io'
Strings are Unicode by default in Python 3.x.
>>> u'python-forum.io' == 'python-forum.io'
True