如何将我的bytearray('b \ x9e \ x18K \ x9a')转换为类似的内容'\ x9e \ x18K \ x9a'< ---只是str而不是array [英] How to convert my bytearray('b\x9e\x18K\x9a') to something like this--> '\x9e\x18K\x9a'<---just str ,not array

查看:219
本文介绍了如何将我的bytearray('b \ x9e \ x18K \ x9a')转换为类似的内容'\ x9e \ x18K \ x9a'< ---只是str而不是array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将我的bytearray('b\x9e\x18K\x9a')转换为类似的内容-> \x9e\x18K\x9a< ---只是str,而不是数组!

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')

我尝试通过

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

但是不能...

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

请帮助我...

推荐答案

在2.x中,字符串是字节字符串.

In 2.x, strings are bytestrings.

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

Latin-1将前256个字符映射为其等效的字节值,因此在Python 3.x中:

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'

这篇关于如何将我的bytearray('b \ x9e \ x18K \ x9a')转换为类似的内容'\ x9e \ x18K \ x9a'&lt; ---只是str而不是array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆