Python-Unicode十六进制字符串解码

2024-09-29 19:35:28 发布

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

我有以下字符串:u'\xe4\xe7\xec\xf7\xe4\xf9\xec\xe9\xf9\xe9'编码在windows-1255中,我想把它解码成Unicode码点(u'\u05d4\u05d7\u05dc\u05e7\u05d4\u05e9\u05dc\u05e9\u05d9')。在

>>> u'\xe4\xe7\xec\xf7 \xe4\xf9\xec\xe9\xf9\xe9'.decode('windows-1255')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\encodings\cp1255.py", line 15, in decode
    return codecs.charmap_decode(input,errors,decoding_table)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

但是,如果我试图解码字符串:'\xe4\xe7\xec\xf7\xe4\xf9\xec\xe9\xf9\xe9'我不会得到异常:

^{pr2}$

如何解码Unicode十六进制字符串(得到异常的字符串)或将其转换为可解码的常规字符串?在

谢谢你的帮助。在


Tags: 字符串inwindowsunicode解码decodexe7xe9
3条回答

I have the following string: u'\xe4\xe7\xec\xf7 \xe4\xf9\xec\xe9\xf9\xe9' encoded in windows-1255

这是自相矛盾的。u表示它是Unicode字符串。但是如果你说它是以任何方式编码的,那么它必须是字节字符串(因为Unicode字符串只能被编码成字节字符串)。在

事实上-你的给定实体-\xe4\xe7等-代表每个字节,并且只有通过给定的编码,windows-1255它们才被赋予各自的含义。在

换句话说,如果你有一个u'\xe4',你可以确保它与u'\u00e4'相同,而不是{},否则就是这样。在

如果您碰巧从一个不知道这个问题的源代码中获得了错误的Unicode字符串,那么您可以从中派生出您真正需要的字节字符串:借助“1:1编码”,即拉丁1。在

所以

correct_str = u_str.encode("latin1")
# now every byte of the correct_str corresponds to the respective code point in the 0x80..0xFF range
correct_u_str = correct_str.decode("windows-1255")

试试这个

>> u'\xe4\xe7\xec\xf7 \xe4\xf9\xec\xe9\xf9\xe9'.encode('latin-1').decode('windows-1255')
u'\u05d4\u05d7\u05dc\u05e7 \u05d4\u05e9\u05dc\u05d9\u05e9\u05d9'

这是因为\xe4\xe7\xec\xf7 \xe4\xf9\xec\xe9\xf9\xe9是一个字节数组,而不是Unicode字符串:字节表示有效的windows-1255字符,而不是有效的Unicode code points。在

因此,在它前面加上u时,Python解释器无法解码字符串,甚至无法打印它:

>>> print u'\xe4\xe7\xec\xf7 \xe4\xf9\xec\xe9\xf9\xe9'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

因此,为了将字节数组转换为UTF-8,必须将其解码为windows-1255,然后将其编码为utf-8

^{pr2}$

希伯来文原文如下:

>>> print '\xd7\x94\xd7\x97\xd7\x9c\xd7\xa7 \xd7\x94\xd7\xa9\xd7\x9c\xd7\x99\xd7\xa9\xd7\x99'
החלק השלישי

相关问题 更多 >

    热门问题