如何将具有非 ASCII 字节的字节数组转换为 python 中的字符串? [英] How to convert bytearray with non-ASCII bytes to string in python?

查看:35
本文介绍了如何将具有非 ASCII 字节的字节数组转换为 python 中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 Python 的位数组包含非 ASCII 字节,我不知道如何将其转换为字符串.示例:

<预><代码>>>>字符串='\x9f'>>>数组=字节数组(字符串)>>>大批bytearray(b'\x9f')>>>数组.解码()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>UnicodeDecodeError: 'ascii' 编解码器无法解码位置 0 中的字节 0x9f:序号不在范围内 (128)

在我的示例中,我只想以某种方式从字节数组中取回字符串 '\x9f'.这可能吗?

解决方案

在 Python 2 中,只需将其传递给 str():

<预><代码>>>>导入系统;sys.version_infosys.version_info(major=2,minor=7,micro=8,releaselevel='final',serial=0)>>>字符串='\x9f'>>>数组=字节数组(字符串)>>>大批bytearray(b'\x9f')>>>字符串(数组)'\x9f'

在 Python 3 中,您希望将其转换回 bytes 对象:

<预><代码>>>>字节(数组)b'\x9f'

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?

解决方案

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'

这篇关于如何将具有非 ASCII 字节的字节数组转换为 python 中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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