Python使用特殊字符编码URL [英] Python encode url with special characters
本文介绍了Python使用特殊字符编码URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用特殊字符编码URL.就我而言,它是:š, ä, õ, æ, ø
(它不是一个有限列表).
I want to encode URL with special characters. In my case it is: š, ä, õ, æ, ø
(it is not a finite list).
urllib2.quote(symbol)
给出非常奇怪的结果,这是不正确的.这些符号还可以如何编码?
urllib2.quote(symbol)
gives very strange result, which is not correct. How else these symbols can be encoded?
推荐答案
urllib2.quote("Grønlandsleiret, Oslo, Norway")
给出%27Gr%B8nlandsleiret%2C%20Oslo%2C%20Norway%27
然后显式使用UTF-8:
Use UTF-8 explicitly then:
urllib2.quote(u"Grønlandsleiret, Oslo, Norway".encode('UTF-8'))
并始终在文件中声明编码.参见 PEP 0263 .
And always state the encoding in your file. See PEP 0263.
非UTF-8字符串需要首先解码,然后编码:
A non-UTF-8 string needs to be decode first, then encoded:
# You've got a str "s".
s = s.decode('latin-1') # (or what the encoding might be …)
# Now "s" is a unicode object.
s = s.encode('utf-8') # Encode as UTF-8 string.
# Now "s" is a str again.
s = urllib2.quote(s) # URL encode.
# Now "s" is encoded the way you need it.
这篇关于Python使用特殊字符编码URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文