【问题标题】:Why is my_str.decode('utf-8') still failing? [duplicate]为什么 my_str.decode('utf-8') 仍然失败? [复制]
【发布时间】:2020-09-14 02:24:32
【问题描述】:

我相信 unicode 三明治。我使用 unicode 三明治。那么为什么当我在字节字符串(py 2.7)上运行以下内容时......

label = label.decode("utf-8")

我仍然收到错误:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 385, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 648, in __protected_call__
    return self.run(*args, **kwargs)
  File "/opt/celery/cl/scrapers/tasks.py", line 638, in update_docket_info_iquery
    d = update_docket_metadata(d, report.metadata)
  File "/usr/local/lib/python2.7/site-packages/juriscraper/pacer/case_query.py", line 166, in metadata
    self._get_label_value_pair(bold, True, field_names)
  File "/usr/local/lib/python2.7/site-packages/juriscraper/pacer/docket_report.py", line 233, in _get_label_value_pair

    label = label.decode("utf-8") <---- Shouldn't this work?

  File "/usr/local/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 6: ordinal not in range(128)

而且,当我尝试在崩溃的线路上进行 decode 时,为什么会抛出 UnicodeEncodeError

我很困惑。再次。

【问题讨论】:

  • 什么是“标签”?您能否将其添加到问题中?
  • 我认为它是因为字节串不是有效的 utf8
  • label 是如何创建的?
  • 你得到了一个UnicodeEncodeError,表明label已经是一个Unicode字符串。 Python 2.7 在尝试将其解码为 UTF-8 之前,使用默认的 ascii 编解码器将其隐式编码回字节字符串,并且由于字符串中的非 ASCII 字符,该隐式编码失败。这是 Python 3 修复的问题之一。

标签: python python-2.7 unicode decode encode


【解决方案1】:

您的日志显示了答案:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 6: ordinal not in range(128)

Python 2.7 无法解码字符串中的字符,因为它是非 ASCII 字符。这里的解决方案是完全在 unicode 中工作,或者先对其进行编码,然后使用适当的编解码器对其进行解码。

问题可能重复:UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    相关资源
    最近更新 更多