2015-01-02 36 views
1

我希望在我的项目中使用unicode而不是str作为所有字符串。我正在尝试使用str.encode方法,但无法从文档中了解encode方法确切地做什么或期望作为输入。str.encode期望输入什么内容?

希腊小写字母pi是U + 03C0,当用UTF-8编码时是0xCF 0x80。我得到如下:

>>> s1 = '\xcf\x80' 
>>> s1.encode('utf-8','ignore') 

Traceback (most recent call last): 
    File "<pyshell#61>", line 1, in <module> 
    s1.encode('utf-8','ignore') 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcf in position 0: ordinal not in range(128) 

我试了:

>>> s2='\x03\xc0' 

>>> s2.encode('utf-8','ignore') 

Traceback (most recent call last): 
    File "<pyshell#62>", line 1, in <module> 
    s2.encode('utf-8','ignore') 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc0 in position 1: ordinal not in range(128) 

是什么encode期望作为输入,以及为何“忽略”选项不可忽视的错误?我尝试'替换',也没有掩盖错误。

回答

3

在Python 2.x中,str是一个字节字符串(编码)。您可以将其解码为unicode对象:

>>> s1 = '\xcf\x80' # string literal (str) 
>>> s1.decode('utf-8') 
u'\u03c0' 

对Unicode的对象,你可以做编码:

>>> u1 = u'\u03c0' # unicode literal (unicode) U+03C0 
>>> u1.encode('utf-8') 
'\xcf\x80'