16

我在用 utf-8 编码字符时遇到了麻烦。我正在使用 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

4

2 回答 2

21

您正在尝试编码/解码字符串,而不是 Unicode 字符串。以下语句确实有效:

u'ç'.encode('utf8')
u'á'.encode('utf-8')
unicode(u'ç')
u'ç'.encode('utf-8','ignore')
于 2013-09-16T11:59:57.667 回答
3

使用u'...',没有u前缀它是字节字符串而不是 unicode 字符串。:

>>> u'ç'.encode('utf8')
'\xc3\xa7'
于 2013-09-16T11:59:45.563 回答