2013-02-21 52 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