2009-07-03 45 views
1

我在嘗試將UTF-8字符串轉換爲unicode時遇到了問題。我收到錯誤。Python Unicode UnicodeEncodeError

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) 

回答

8

正確solution是做到以下幾點:

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

試試這個:

self.response.headers['Location'] = absolute_url.decode("utf-8") 
or 
self.response.headers['Location'] = unicode(absolute_url, "utf-8") 
+0

比較遺憾的是沒有工作。 這是我現在的代碼。因爲我調用self.redirect,字符串正在編碼並導致錯誤,因爲在這種情況下,URL實際上有一個「å」。如果發生此錯誤,那麼我將網址寫入頁面,並使用META-REFRESH標記,讓瀏覽器在幾秒鐘後重定向 self.redirect(url.long_url) – 2009-07-03 02:45:11

+0

@zdmytriv:unicode(absolute_url)?不應該在某處提到UTF-8嗎? – 2009-07-03 02:53:05

1

請編輯一塌糊塗,這樣它的清晰。提示:使用「代碼塊」(101010 thingy按鈕)。

你說你是「試圖將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。由於你的Url不是一個Ascii字符串,你會得到這個錯誤。由於位置標題不適用於無效的網址,因此抓取錯誤將無濟於事。

當您創建absolute_url時,您需要確保其編碼正確,最好使用urllib.quote和字符串encode()方法。你可以試試這個:

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