如何将具有非 ASCII 字节的字节数组转换为 python 中的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27657570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert bytearray with non-ASCII bytes to string in python?
提问by Karel Bílek
I don't know how to convert Python's bitarray to string if it contains non-ASCII bytes. Example:
如果 Python 的位数组包含非 ASCII 字节,我不知道如何将其转换为字符串。例子:
>>> 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?
在我的示例中,我只想以某种方式从字节数组中获取字符串 '\x9f' 。那可能吗?
采纳答案by Martijn Pieters
In Python 2, just pass it to str()
:
在 Python 2 中,只需将其传递给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:
在 Python 3 中,您希望将其转换回bytes
对象:
>>> bytes(array)
b'\x9f'
回答by suryakrupa
Did you try
你试过了吗
byteVariable.decode('utf-8')
回答by Tim Poffenbarger
I'd like to mention the binascii
library that comes with Python.
我想提一下binascii
Python 自带的库。
My use case: I was querying a database that had a binary field being used as a key within the DB. I wanted to pull that binary field and treat it as a key elsewhere. I thought converting it to a string was the best use-case.
我的用例:我正在查询一个数据库,该数据库有一个二进制字段用作数据库中的键。我想拉那个二进制字段并将其视为其他地方的密钥。我认为将其转换为字符串是最好的用例。
binascii offered me a better alternative:
binascii 为我提供了一个更好的选择:
import binascii
binary_field = bytearray(b'\x92...')
binascii.hexlify(binary_field)
import binascii
binary_field = bytearray(b'\x92...')
binascii.hexlify(binary_field)