问题描述
我需要解码 UNICODE编码的字符串:
I need to decode a "UNICODE" encoded string:
>>> id = u'abcdß'
>>> encoded_id = id.encode('utf-8')
>>> encoded_id
'abcd\xc3\x9f'
我遇到的问题是:
使用Pylons路由,我将encode_id变量作为Unicode字符串 u'abcd\xc3\x9f'
而不是普通字符串'abcd\xc3\x9f'
:
The problem I have is:Using Pylons routing, I get the encoded_id variable as a unicode string u'abcd\xc3\x9f'
instead of a just a regular string 'abcd\xc3\x9f'
:
使用python,如何解码我的unicode字符串的encode_id变量?
Using python, how can I decode my encoded_id variable which is a unicode string?
>>> 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)
推荐答案
您拥有UTF-8编码的数据(没有诸如UNICODE编码的数据之类的东西)。
You have UTF-8 encoded data (there is no such thing as UNICODE encoded data).
对unicode进行编码值转换为Latin-1,然后从UTF8解码:
Encode the unicode value to Latin-1, then decode from UTF8:
encoded_id.encode('latin1').decode('utf8')
拉丁文1将前255个unicode点一对一映射到字节。
Latin 1 maps the first 255 unicode points one-on-one to bytes.
Demo:
>>> encoded_id = u'abcd\xc3\x9f'
>>> encoded_id.encode('latin1').decode('utf8')
u'abcd\xdf'
>>> print encoded_id.encode('latin1').decode('utf8')
abcdß
这篇关于在Python中解码ENCODED Unicode字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!