【问题标题】:Handle UnicodeEncodeError in python2.7python2.7中处理UnicodeEncodeError
【发布时间】:2019-10-14 02:41:49
【问题描述】:

我有以下代码:

    for index, row in df_out.iterrows():
        yield {
               'CustomerName': str(row['CustomerName'])
              }

我得到了 UnicodeEncodeError:

RuntimeError: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 10: ordinal not in range(128)

如何处理这部分以避免该错误?

str(row['CustomerName'])

【问题讨论】:

  • 复制和粘贴代码会导致 \xe9 所以避免它。 Check This
  • @SantoshKarki 我没有复制/粘贴代码
  • 然后查看上面的链接
  • @SantoshKarki 您链接的帖子是关于源代码中的非 ASCII 字符的。 OP 正在处理输入中的编码问题。

标签: python string unicode character-encoding


【解决方案1】:

如果你可能在 python2 中处理非 ASCII 文本,那么做

str(some_text)

通常是个坏主意,因为如果 some_text 包含非 ASCII 字符,您将得到一个 UnicodeEncodeError。正确的代码是

unicode(some_text)

unicode() 不会尝试将您的文本编码为 ASCII。

但是给出这个代码

for index, row in df_out.iterrows():
    yield {
           'CustomerName': str(row['CustomerName'])
          }

row['CustomerName'] 很可能已经是一个unicode 对象,所以在它上面调用unicode 是多余的。这可能会起作用:

for index, row in df_out.iterrows():
    yield {
           'CustomerName': row['CustomerName']
          }

总结一下:删除str 调用。如果这不起作用,请尝试将 str 替换为 unicode

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2018-07-21
    • 2017-08-04
    • 2014-09-01
    相关资源
    最近更新 更多