How To Convert Bytearray With Non-ascii Bytes To String In Python?
I don't know how to convert Python's bitarray to string if it contains non-ASCII bytes. Example: >>> string='\x9f' >>> array=bytearray(string) >>> array
Solution 1:
In Python 2, just pass it to str()
:
>>>import sys; sys.version_info
sys.version_info(major=2, minor=7, micro=8, releaselevel='final', serial=0)
>>>string='\x9f'>>>array=bytearray(string)>>>array
bytearray(b'\x9f')
>>>str(array)
'\x9f'
In Python 3, you'd want to convert it back to a bytes
object:
>>> bytes(array)
b'\x9f'
Solution 2:
Solution 3:
I'd like to mention the binascii
library that comes with Python.
My use case: I was querying a database that had a binary field being used as a key within the DB. I wanted to pull that binary field and treat it as a key elsewhere. I thought converting it to a string was the best use-case.
binascii offered me a better alternative:
import binascii
binary_field = bytearray(b'\x92...')
binascii.hexlify(binary_field)
Solution 4:
use bytes(array, encoding='utf8')
Post a Comment for "How To Convert Bytearray With Non-ascii Bytes To String In Python?"