确定具有起始字节的项的编码

2024-05-12 18:50:22 发布

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

我最近遇到了这个字符串:b'\xd5\xa3Lk\xd4\xad\xaeH\xb8\xae\xab\xd8EL3\xd1RR\x17\x0c\xea~\xfa\xd0\xc9\xfeJ\x9aq\xd0\xc57\xfd\xfa\x1d}\x8f\x99?*\xef\x88\x1e\x99\x8d\x81t`1\x91\xebh\xc5\x9d\xa7\xa5\x8e\xb9X',我想解码它。 现在我知道这在使用string.decode()的python中是可能的,但它需要编码。如何确定解码此字符串的编码


Tags: 字符串编码解码xb8xd0x99xd5xd4
1条回答
网友
1楼 · 发布于 2024-05-12 18:50:22

我先前对你的问题的评论部分准确,部分错误。从Standard Encodings的文件中:

Without external information it’s impossible to reliably determine which encoding was used for encoding a string. Each charmap encoding can decode any random byte sequence. However that’s not possible with UTF-8, as UTF-8 byte sequences have a structure that doesn’t allow arbitrary byte sequences.

因此,您应该尝试使用“utf-8-sig”进行解码(在一般情况下,字节顺序标记或BOM可能作为前3个字节出现,这是而不是示例中的情况,因此您可以使用“utf-8”)。但是如果失败了,就不能保证您知道使用试错解码使用的是什么编码,因为根据上述文档,尝试使用另一个编解码器解码可能会成功(并可能给您带来垃圾)。如果“utf-8”解码成功,则使用的编码可能是。见下文

s = 'abcde'
print(s.encode('utf-32').decode('utf-16'))
print(s.encode('cp500').decode('latin-1'))

印刷品:

 a b c d e
�����

当然,“utf-8”编码也将成功解码使用“ascii”编解码器编码的字符串,因此存在这种程度的不确定性

相关问题 更多 >