Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert my bytearray('b\x9e\x18K\x9a') to something like this--> '\x9e\x18K\x9a'<---just str ,not array

How to convert my bytearray('b\x9e\x18K\x9a') to something like this --> \x9e\x18K\x9a <---just str, not array!

>> uidar = bytearray()
>> uidar.append(tag.nti.nai.uid[0])
>> uidar.append(tag.nti.nai.uid[1])
>> uidar.append(tag.nti.nai.uid[2])
>> uidar.append(tag.nti.nai.uid[3])
>> uidar
   bytearray('b\x9e\x18K\x9a')

I try to decode my bytearray by

uid  =  uidar.decode('utf-8')

but it can't...

Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    uid = uidar.decode("utf-8")
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x9e in position 0: invalid start byte

Help me Please ...

like image 546
user1376294 Avatar asked May 05 '12 05:05

user1376294


1 Answers

In 2.x, strings are bytestrings.

>>> str(bytearray('b\x9e\x18K\x9a'))
'b\x9e\x18K\x9a'

Latin-1 maps the first 256 characters to their bytevalue equivalents, so in Python 3.x:

3>> bytearray(b'b\x9e\x18K\x9a').decode('latin-1')
'b\x9e\x18K\x9a'
like image 100
Ignacio Vazquez-Abrams Avatar answered Oct 31 '22 14:10

Ignacio Vazquez-Abrams