Python Unicode 编码错误

1 投票
4 回答
3432 浏览
提问于 2025-04-15 12:39

我在尝试把一个UTF-8字符串转换成unicode时遇到了问题,出现了错误。

UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128)

我试着把这个代码放在一个try/except块里,但谷歌却给了我一个系统管理员错误,只有一行内容。有没有人能建议我怎么捕捉这个错误并继续执行?

谢谢,约翰。

-- 完整错误信息 --

Traceback (most recent call last):
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__
    handler.get(*groups)
  File "/Users/johnb/Sites/hurl/hurl.py", line 153, in get
    self.redirect(url.long_url)
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 371, in redirect
    self.response.headers['Location'] = str(absolute_url)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128)

4 个回答

1

请把那个乱七八糟的内容整理一下,让人能看得懂。提示:使用“代码块”(就是那个101010的按钮)。

你说你在“尝试把一个UTF-8字符串转换成unicode”,但是用str(absolute_url)这种方式有点奇怪。你确定absolute_url是UTF-8格式吗?可以试试:

print type(absolute_url)
print repr(absolute_url)

如果它确实是UTF-8格式,你需要用absolute_url.decode('utf8')来解码。

4

你想设置的“位置”头信息需要是一个网址,而网址必须是用Ascii字符表示的。因为你的网址不是Ascii字符串,所以出现了错误。仅仅捕捉这个错误是没用的,因为无效的网址会导致“位置”头信息无法正常工作。

在创建 absolute_url 时,你需要确保它被正确编码,最好的方法是使用 urllib.quote 和字符串的 encode() 方法。你可以试试这个:

self.response.headers['Location'] = urllib.quote(absolute_url.encode('utf-8'))
8

正确的解决办法是这样做:

self.response.headers['Location'] = urllib.quote(absolute_url.encode("utf-8"))

撰写回答