【问题标题】:How to handle UnicodeDecodeError如何处理 UnicodeDecodeError
【发布时间】:2020-09-07 08:37:53
【问题描述】:
str1="khloé kardashian"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 4: ordinal not in range(128)

如何以完美的方式对其进行编码。 我正在尝试在烧瓶应用程序的 URL 中替换它:它在命令行上运行良好,但在应用程序中返回上述错误:

>>> url ="google.com/q=apple"
>>> url.replace("q=apple", "q={}".format(str1))
'google.com/q=khlo\xc3\xa9 kardashian'

【问题讨论】:

标签: python python-2.7 unicode python-unicode unicode-string


【解决方案1】:

您应该使用urllib 来正确构造 URL。您的 URL 中还有其他问题,例如空格。 urllib 照顾他们。

params = {'q': str1}    
"google.com/" + urllib.urlencode(params)
#'google.com/q=khlo%C3%A9%20kardashian'

【讨论】:

  • 在 Python 3 中,旧的 urllib 模块被拆分为一个包,urllib.parse 具有处理 URL 内容的相关工具(例如 this)。我相应地修复了代码示例。
  • @KarlKnechtel OP 使用 2.7。因此,解决方案适用于 2.7。
  • 哦,天哪。才注意到这一点。很失望这仍然是一件事(特别是对于明确围绕 Unicode 的问题),但我想我对此无能为力。
【解决方案2】:

改用 utf-8

str1="khloé kardashian"
str1.encode("utf-8")

【讨论】:

  • &gt;&gt;&gt; str1.encode("utf-8") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)
  • 确保您从代码中删除了“str1.encode("ascii")”
【解决方案3】:

根据标准,URL 中不能包含 é。您需要使用the appropriate URL encoding,其中is handled由内置的urllib包。

【讨论】:

  • 有一个单独的方案称为idna,用于处理域名中的Unicode字符,以便浏览器可以向用户显示Unicode,同时向DNS发送更老式的东西。这也在urllib 包中提供。参见例如stackoverflow.com/questions/41067320/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
  • 2012-09-19
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 2012-04-30
  • 1970-01-01
相关资源
最近更新 更多