在Python3.6中将字节转换为字符串

2024-05-16 01:39:07 发布

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

我正在尝试读取和处理一个文件。这在Python2.7中运行得非常好,但我无法在Python 3中运行它。 在Python2.7中,它在不提供任何编码的情况下工作,而在Python3中,我尝试了有编码和无编码的所有组合。

经过深入研究,我发现read返回的内容在两个版本中是不同的。

在Python2.7中工作的代码:

>>> f = open('resource.cgn', 'r')
>>> content = f.read()
>>> type(content)
<type 'str'>
>>> content[0:20]
'\x04#lwq \x7f`g \xa0\x03\xa3,ess to'
>>> content[0]
'\x04'

但是在Python 3中:

>>> f = open('resource.cgn','r')
>>> content = f.read()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
  UnicodeDecodeError: 'ascii' codec cant decode byte 0xa0 in position 10: ordinal not in range(128)
>>> f = open('resource.cgn','rb')
>>> content = f.read()
>>> type(content)                   
<class 'bytes'>
>>> content[0:20]
b'\x04#lwq \x7f`g \xa0\x03\xa3,ess to'
>>> content[0]
4
>>> content.decode('utf8')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 10: 
invalid start byte

我希望得到与Python2.7中相同的输出。content应该是string类型,content[0]应该是str'\x04',而不是int4

有什么线索可以告诉我怎么得到这个吗?我试过编码,但没有成功。


Tags: in编码readtypelineasciiopencontent
1条回答
网友
1楼 · 发布于 2024-05-16 01:39:07

默认情况下,3.X的str现在是2.X的unicode,在3.X中以文本模式打开的文件对象分别在读取或写入文件时尝试解码和编码。^2.X的{}现在是3.X中的bytes。3.X bytes和2.X的str之间确实有非常小的差别,两者基本上都包含8位文本。

下面是在3.X中将b'\x04#lwq \x7f`g \xa0\x03\xa3,ess to'转换为str的一个简单技巧:

>>> content = ''.join(chr(x) for x in b'\x04#lwq \x7f`g \xa0\x03\xa3,ess to')
>>> content
'\x04#lwq \x7f`g \xa0\x03£,ess to'
>>> content[0]
'\x04

解码bytes字符串失败,因为您有无效的UTF-8字符字节,与ASCII相同。

但是,明智的做法是,bytes用于处理二进制数据,而str仅用于3.X中的Unicode字符串。建议使用bytes,而不是str用于3.X中的二进制字符串:

>>> content = b'\x04#lwq \x7f`g \xa0\x03\xa3,ess to'
>>> hex(content[0])
'0x4'

相关问题 更多 >