我需要解码一个"UNICODE“编码字符串:
>>> id = u'abcdß'
>>> encoded_id = id.encode('utf-8')
>>> encoded_id
'abcd\xc3\x9f'我遇到的问题是:使用幽门路由,我将encoded_id变量作为unicode字符串u'abcd\xc3\x9f',而不是普通的字符串'abcd\xc3\x9f'。
使用python,我如何解码我的encoded_id变量,即unicode字符串?
>>> encoded_id = u'abcd\xc3\x9f'
>>> encoded_id.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/test/vng/lib64/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 4-5: ordinal not in range(128)发布于 2013-09-27 17:42:40
您有UTF-8编码数据(没有UNICODE编码的数据)。
将unicode值编码为拉丁文-1,然后从UTF8解码:
encoded_id.encode('latin1').decode('utf8')拉丁文1将首255个unicode点一对一映射为字节.
演示:
>>> encoded_id = u'abcd\xc3\x9f'
>>> encoded_id.encode('latin1').decode('utf8')
u'abcd\xdf'
>>> print encoded_id.encode('latin1').decode('utf8')
abcdßhttps://stackoverflow.com/questions/19056863
复制相似问题