我有以下字符串:u'\xe4\xe7\xec\xf7\xe4\xf9\xec\xe9\xf9\xe9' 在 windows-1255 中编码,我想将其解码为 Unicode 代码点 (u'\u05d4\u05d7\u05dc\u05e7\u05d4\u05e9\u05dc\u05d9\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' 我没有得到异常:
>>> '\xe4\xe7\xec\xf7 \xe4\xf9\xec\xe9\xf9\xe9'.decode('windows-1255')
u'\u05d4\u05d7\u05dc\u05e7 \u05d4\u05e9\u05dc\u05d9\u05e9\u05d9'
如何解码 Unicode 十六进制字符串(出现异常的字符串)或将其转换为可解码的常规字符串?
感谢您的帮助。
请您参考如下方法:
I have the following string:
u'\xe4\xe7\xec\xf7 \xe4\xf9\xec\xe9\xf9\xe9'encoded inwindows-1255
这是自相矛盾的。 u 表示它是一个 Unicode 字符串。但是如果说用什么编码,那肯定是字节串(因为Unicode字符串只能编码成字节串)。
事实上 - 你给定的实体 - \xe4\xe7 等 - 每个代表一个字节,并且只有通过给定的编码,windows-1255 他们才能获得它们各自的含义。
换句话说,如果您有一个 u'\xe4',您可以确定它与 u'\u00e4' 相同,而不是 u'\u05d4' 否则就是这种情况。
如果你偶然从一个不知道这个问题的来源得到了错误的 Unicode 字符串,你可以从中导出你真正需要的字节字符串:借助“1:1 编码”,是 latin1。
所以
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")
