UnicodeDecodeError:'ascii'编解码器无法解码位置0处的字节0xe7:128范围之外的序数。

16

我希望你能帮助翻译一下关于IT技术的内容,涉及字符编码问题。我正在使用Django,在尝试发送非纯文本Android通知时遇到了问题。我试图找到错误的源头,并成功地确定了错误的源头不在我的项目中。

在Python shell中,我输入:

'ç'.encode('utf8')

我遇到了这个错误:

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

我遇到了相同的错误:

'á'.encode('utf-8')
unicode('ç')
'ç'.encode('utf-8','ignore')

我使用smart_text、force_text和smart_bytes时出现了错误。

这是Python、我的操作系统还是其他问题导致的呢?

我在Red Hat版本4.4.7-3上运行Python 2.6.6。

2个回答

21

您正在尝试编码/解码字符串,而不是Unicode字符串。以下语句可以正常工作:

u'ç'.encode('utf8')
u'á'.encode('utf-8')
unicode(u'ç')
u'ç'.encode('utf-8','ignore')

3

使用 u'...',不带前缀 u 则是字节字符串而非Unicode字符串。

>>> u'ç'.encode('utf8')
'\xc3\xa7'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接