Reputation:
I want to convert a variable containing a bytes
object of Ascii data to a string.
Ex:
a=bytearray(b'31303031')
I want to convert it to:
'1001'
How to do this in Python3?
Upvotes: 0
Views: 133
Reputation: 26005
Convert each pair to integer from base 16, get the appropriate character, and concatenate:
''.join(chr(int(a[i:i+2], 16)) for i in range(0,len(a),2))
Of course, you do not really have a bytes
object of hexadecimals, but a string. So, get back the string, make a real hexadecimal bytes
object, and decode that is another option:
bytes.fromhex(a.decode('ascii')).decode('ascii')
Upvotes: 1