2013-02-21 54 views
0

如何將unicode編碼爲urlenconing中的python 2.7如何將unicode編碼爲python 2.7中的urlenconing?

我想編碼像'€'的Unicode。

但我卻不知道該怎麼辦......

>>> u='€' 
>>> _u=u'€' 
>>> u 
'\xa2\xe6' 
>>> _u 
u'\u20ac' 
>>> urllib.quote(u) 
'%A2%E6' 
>>> urllib.quote(_u) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Python27\lib\urllib.py", line 1268, in quote 
    return ''.join(map(quoter, s)) 
KeyError: u'\u20ac' 
>>> print urllib.unquote(urllib.quote(u)) 
€ 
>>> 

只是我需要 '%A2%E6' 通過unicode的 '€'。

我該怎麼辦?

>>> print urllib.unquote(urllib.quote(u'€'.encode('utf8'))) 
? 
+0

編碼爲utf-8,然後一切順利。 http://stackoverflow.com/questions/5557849/is-there-a-unicode-ready-substitute-i-can-use-for-urllib-quote-and-urllib-unquot – fanlix 2013-02-21 07:34:15

+0

謝謝@fanlix,我讀你的鏈接。但我仍然不知道。該鏈接說使用encode()。所以我試了一下。請參閱上文。 – chobo 2013-02-21 07:45:52

回答

0

你應該encode unicode字符串,然後使用urllib.quote。你自己寫了你的問題的答案

urllib.quote(u'€'.encode('utf8')) 
+0

謝謝。你的回答很好。但'urllib.unquote('%E2%82%AC')'返回'%E2%82%AC'。 ''urllib.unquote('%E2%82%AC'')'return'?' – chobo 2013-02-21 08:41:43

+0

在我的電腦腳本輸出正確的結果:'''。可能你的問題是「糟糕」stdout編碼?嘗試運行下面的代碼'urllib.unquote(urllib.quote(U '€' .encode( 'utf-8')))解碼( 'utf-8')' – 2013-02-21 12:32:06