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

2024-06-16 09:58:32 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将我的bytearray('b\x9e\x18K\x9a')转换为类似这样的-->;\x9e\x18K\x9a<;——仅str,而不是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

请帮帮我。。。


Tags: inuidtaglineutffiledecodeappend
1条回答
网友
1楼 · 发布于 2024-06-16 09:58:32

在2.x中,字符串是bytestrings。

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

Latin-1将前256个字符映射到它们的字节值等价物,因此在Python3.x中:

3>> bytearray(b'b\x9e\x18K\x9a').decode('latin-1')
'b\x9e\x18K\x9a'

相关问题 更多 >