2013-09-27 47 views
3

一个编码的Unicode字符串我需要解码“UNICODE”编码字符串:解码在Python

>>> 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) 
+0

如果可能的话,你应该弄清楚为什么你从主塔incorreclty得到的字符串解码为'拉丁1'(或它的近亲,'Windows的1252'),而不是'UTF -8'开头。 –

回答

4

你有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ß