【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4'UnicodeEncodeError: 'ascii' 编解码器无法编码字符 u'\xe4'
【发布时间】:2014-12-22 22:50:47
【问题描述】:

我永久收到以下错误:

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")

但是,没有任何效果。

【问题讨论】:

  • u'\xe4'.encode('ascii','ignore') 适合我。我们需要更多的上下文来了解真正的问题是什么。
  • #2 也“有效”,因为它会产生没有错误的结果;不能说这是否是预期的结果。

标签: python encoding ascii


【解决方案1】:

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

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

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

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

在 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

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

【讨论】:

  • python3还有其他解决方案吗?
猜你喜欢
  • 2013-04-21
  • 2015-04-13
  • 2018-07-07
  • 2011-04-05
  • 2016-09-10
  • 2023-03-24
  • 1970-01-01
  • 2015-10-21
相关资源
最近更新 更多