Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
bytearray(b'\x9f')
>>> array.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 0: ordinal not in range(128)

In my example, I just want to somehow get a string '\x9f' back from the bytearray. Is that possible?

like image 999
Karel Bílek Avatar asked Dec 26 '14 13:12

Karel Bílek


People also ask

Which method converts raw byte data to string in Python?

String encode() and decode() method provides symmetry whereas bytes() constructor is more object-oriented and readable approach. You can choose any of them based on your preference.

What is Bytearray data type in Python?

The bytearray type is a mutable sequence of integers in the range between 0 and 255. It allows you to work directly with binary data. It can be used to work with low-level data such as that inside of images or arriving directly from the network. Bytearray type inherits methods from both list and str types.


2 Answers

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'
like image 159
Martijn Pieters Avatar answered Nov 15 '22 21:11

Martijn Pieters


Did you try

byteVariable.decode('utf-8')
like image 37
suryakrupa Avatar answered Nov 15 '22 19:11

suryakrupa