我有以下字符串: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十六进制字符串(得到异常的字符串)或将其转换为可解码的常规字符串?在
谢谢你的帮助。在
这是自相矛盾的。
u
表示它是Unicode字符串。但是如果你说它是以任何方式编码的,那么它必须是字节字符串(因为Unicode字符串只能被编码成字节字符串)。在事实上-你的给定实体-
\xe4\xe7
等-代表每个字节,并且只有通过给定的编码,windows-1255
它们才被赋予各自的含义。在换句话说,如果你有一个},否则就是这样。在
u'\xe4'
,你可以确保它与u'\u00e4'
相同,而不是{如果您碰巧从一个不知道这个问题的源代码中获得了错误的Unicode字符串,那么您可以从中派生出您真正需要的字节字符串:借助“1:1编码”,即拉丁1。在
所以
试试这个
这是因为
\xe4\xe7\xec\xf7 \xe4\xf9\xec\xe9\xf9\xe9
是一个字节数组,而不是Unicode字符串:字节表示有效的windows-1255
字符,而不是有效的Unicode code points。在因此,在它前面加上
u
时,Python解释器无法解码字符串,甚至无法打印它:因此,为了将字节数组转换为UTF-8,必须将其解码为
^{pr2}$windows-1255
,然后将其编码为utf-8
:希伯来文原文如下:
相关问题 更多 >
编程相关推荐