如何处理UnicodeDecodeError

2024-09-30 16:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

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

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

Tags: incom应用程序urlapplemostgooglecall
3条回答

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

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

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

改用utf-8

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

相关问题 更多 >