2011-11-14 59 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'