UnicodeEncodeError: 'ascii' 编解码器无法编码字符 u'xe4' [英] UnicodeEncodeError: 'ascii' codec can't encode character u'xe4'

查看:29
本文介绍了UnicodeEncodeError: 'ascii' 编解码器无法编码字符 u'xe4'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我永久收到以下错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'xe4' in position 27: ordinal not in range(128)

我已经试过了

  1. x.encode("ascii", "ignore")
  2. x.encode("utf-8")
  3. x.decode("utf-8")

然而,没有任何效果.

解决方案

你必须从源头上发现这个字符是哪种编码.

我猜这是 ISO-8859-1(欧洲语言),在这种情况下是ä",但您应该检查一下.它也可以是西里尔字母或希腊字母.

参见 http://en.wikipedia.org/wiki/ISO/IEC_8859-1 获取此编码中字符的完整列表.

使用此信息,您可以要求 Python 对其进行转换:

在 Python 2.7 中

<预><代码>>>>s = 'xe4'>>>t = s.decode('iso-8859-1')>>>打印 t一个>>>对于 c in t:... 打印 ord(c)...228>>>u = t.encode('utf-8')>>>打印你一个>>>对于以字节(u)为单位的 c:... 打印 ord(c)...195164

String t 在 Python 中以 ISO-8859-1 内部编码.字符串 u 在内部以 UTF-8 编码,该字符在 UTF-8 中占 2 个字节.另请注意,print 指令知道"如何显示这些不同的编码.

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.encode("utf-8")
  3. x.decode("utf-8")

However, nothing works.

解决方案

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.

See http://en.wikipedia.org/wiki/ISO/IEC_8859-1 for a complete list of characters in this encoding.

Using this information, you can ask Python to convert it :

In 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.

这篇关于UnicodeEncodeError: 'ascii' 编解码器无法编码字符 u'xe4'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆