0

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?

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.