Python UnicodeDecodeError: 'ascii' 编解码器无法解码位置 0 中的字节 0xe7:序号不在范围内 (128)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18827396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:58:11  来源:igfitidea点击:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 0: ordinal not in range(128)

pythondjangoencodingutf-8redhat

提问by lluisu

I'm having troubles in encoding characters in utf-8. I'm using Django, and I get this error when I tried to send an Android notification with non-plain text. I tried to find where the source of the error and I managed to figure out that the source of the error is not in my project.

我在用 utf-8 编码字符时遇到了麻烦。我正在使用 Django,当我尝试使用非纯文本发送 Android 通知时出现此错误。我试图找到错误的来源,并设法找出错误的来源不在我的项目中。

In python shell, I type:

在 python shell 中,我输入:

'?'.encode('utf8')

and I get this error:

我收到这个错误:

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)

I get the same errors with:

我收到相同的错误:

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

I get errors with smart_text, force_text and smart_bytes too.

我也收到 smart_text、force_text 和 smart_bytes 错误。

Is that a problem with Python, my OS, or another thing?

这是 Python、我的操作系统还是其他方面的问题?

I'm running Python 2.6.6 on a Red Hat version 4.4.7-3

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

采纳答案by Simeon Visser

You're trying to encode / decode strings, not Unicode strings. The following statements do work:

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

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

回答by Ashwini Chaudhary

Use u'...', without the uprefix it is byte-string not a unicode string.:

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

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