Python UnicodeEncodeError: 'ascii' 编解码器无法编码字符 u'\xe4'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26592988/
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
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4'
提问by toom
I permanently get the following error:
我永久收到以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 27: ordinal not in range(128)
I already tried
我已经试过了
x.encode("ascii", "ignore")x.encode("utf-8")x.decode("utf-8")
x.encode("ascii", "ignore")x.encode("utf-8")x.decode("utf-8")
However, nothing works.
但是,没有任何效果。
回答by Micka?l Bucas
You have to discover in which encoding is this character at the source.
您必须在源头上发现此字符采用哪种编码。
I guess this is ISO-8859-1 (european languages), in which case it's "?", but you should check. It could also be cyrillic or greek.
我猜这是 ISO-8859-1(欧洲语言),在这种情况下是“?”,但您应该检查一下。它也可以是西里尔字母或希腊字母。
See http://en.wikipedia.org/wiki/ISO/IEC_8859-1for a complete list of characters in this encoding.
有关此编码中字符的完整列表,请参阅http://en.wikipedia.org/wiki/ISO/IEC_8859-1。
Using this information, you can ask Python to convert it :
使用此信息,您可以要求 Python 对其进行转换:
In Python 2.7
在 Python 2.7 中
>>> s = '\xe4'
>>> t = s.decode('iso-8859-1')
>>> print t
?
>>> for c in t:
... print ord(c)
...
228
>>> u = t.encode('utf-8')
>>> print u
?
>>> for c in bytes(u):
... print ord(c)
...
195
164
String tis internally encoded in ISO-8859-1 in Python. String uis internally encoded in UTF-8, and that character takes 2 bytes in UTF-8. Notice also that the printinstruction "knows" how to display these different encodings.
字符串t在 Python 中以 ISO-8859-1 内部编码。字符串u在内部以 UTF-8 编码,该字符在 UTF-8 中占用 2 个字节。另请注意,该print指令“知道”如何显示这些不同的编码。

