我在这方面遇到的麻烦比我想承认的要多得多。我已经查看了许多帖子,但都没有运气。我正在尝试像这样转换一个字节对象:
b = b'%PDF-1.5\r%\xe2\xe3\xcf\xd3\r\n'
转换为字符串变量。
我已经尝试过以下几种方法:
import codecs
codecs.decode(b, 'hex')
# Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)
b.decode('hex')
# LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
b.unhexlify(_)
#AttributeError: 'bytes' object has no attribute 'unhexlify'
str(b)
# just gives me the same bytes object with str type
b.decode('utf-8')
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte
有人能告诉我我哪里做错了吗?
发布于 2018-06-07 04:00:49
实际上b
已经是一个字符串了。您可以通过类型检查和验证它是否打印所有特殊字符来了解它:
>>> b = b'%PDF-1.5\r%\xe2\xe3\xcf\xd3\r\n'
>>> type(b)
<type 'str'>
>>> print(b)
%ÔѤË1.5
>>>
如果有实数字节对象,可以使用.decode(encoding)
将字节转换为字符串。糟糕的是,你需要知道你的编码才能做到这一点。
我用这个网站上的几个编码进行了反复试验:https://docs.python.org/2.4/lib/standard-encodings.html。它没有产生iso8859_15的错误,但我不能保证它是一个好的错误。下面是一个代码片段:
line.decode('iso8859_15')
https://stackoverflow.com/questions/50728405
复制相似问题