UnicodeEncodeError:“ascii”编解码器无法编码字符u'\xe4'

时间:2022-06-12 20:19:55

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

我已经试过

  1. x.encode("ascii", "ignore")
  2. x。编码(“ascii”,“忽略”)
  3. x.encode("utf-8")
  4. x.encode(“utf - 8”)
  5. x.decode("utf-8")
  6. x.decode(“utf - 8”)

However, nothing works.

然而,没有效果。

1 个解决方案

#1


9  

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(欧洲语言),在这种情况下是a,但是你应该检查一下。也可以是西里尔语或希腊语。

See http://en.wikipedia.org/wiki/ISO/IEC_8859-1 for 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 t is internally encoded in ISO-8859-1 in Python. String u is internally encoded in UTF-8, and that character takes 2 bytes in UTF-8. Notice also that the print instruction "knows" how to display these different encodings.

字符串t在Python中内部编码为ISO-8859-1。字符串u在内部编码为UTF-8,该字符在UTF-8中占用2个字节。还要注意,print指令“知道”如何显示这些不同的编码。

#1


9  

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(欧洲语言),在这种情况下是a,但是你应该检查一下。也可以是西里尔语或希腊语。

See http://en.wikipedia.org/wiki/ISO/IEC_8859-1 for 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 t is internally encoded in ISO-8859-1 in Python. String u is internally encoded in UTF-8, and that character takes 2 bytes in UTF-8. Notice also that the print instruction "knows" how to display these different encodings.

字符串t在Python中内部编码为ISO-8859-1。字符串u在内部编码为UTF-8,该字符在UTF-8中占用2个字节。还要注意,print指令“知道”如何显示这些不同的编码。