2011-11-14 66 views
1

當我嘗試編碼西里爾字符「Р」字符時,出現錯誤。這裏是我的代碼和錯誤:無法在Python 2.7.x中編碼西里爾文字符

>>> "Р".encode('utf8') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128) 

如何解決它。請幫幫我。我正在使用Python 2.7.x.感謝您的每一個建議。

編輯:

def _to_unicode_or_bust(self, obj, encoding='utf-8'): 
    if isinstance(obj, basestring): 
     if not isinstance(obj, unicode): 
      obj = unicode(obj, encoding) 
    return obj 

我得到從上面介紹的方法。它在終端和簡單的python文件中工作。這在OpenERP中不起作用。

回答

2

Python 2.x中的任何""(例如str)都已編碼。您需要將其解碼爲unicode,然後才能將其編碼爲其他內容。

"Unicode In Python, Completely Demystified"

+0

更重要的是,如果我們開始與文字,創建Unicode文本('U「Р 「')首先。 –

+0

它正在處理終端和簡單的python文件。但它現在在OpenERP上工作。看我的編輯。 – Zeck

+0

PowerPoint幻燈片似乎是一種揭祕事物的糟糕方式。 – GrandAdmiral

0

Python的解釋中開始,所以你不能直接輸入Cyrllic字符的ASCII唯一模式。相反,你可以通過它們的代碼點號創建它們:

>>> print unichr(0x420) 
Р 
>>> unichr(0x420).encode('utf-8') 
'\xd0\xa0' 

或他們的名字:

>>> u'\N{CYRILLIC CAPITAL LETTER ER}'.encode('utf-8') 
'\xd0\xa0'