25

次の文字列があるとします。

"http://earth.google.com/gallery/kmz/women_for_women.kmz?a=large"

上記のような文字列を、すべての文字がURLに準拠するように変更される以下の文字列に変換できる関数またはモジュールはありますか?

"http%3A%2F%2Fearth.google.com%2Fgallery%2Fkmz%2Fwomen_for_women.kmz%3Fa%3Dlarge"

Pythonでこれを行うための最良の方法は何ですか?

4

3 に答える 3

32

Python 2のurllib.quote_plus、およびPython3のurllib.parse.quote_plus

url = "http://earth.google.com/gallery/kmz/women_for_women.kmz?a=large"
# Python 2
urllib.quote_plus(url)
# Python 3
urllib.parse.quote_plus(url)

出力:

'http%3A%2F%2Fearth.google.com%2Fgallery%2Fkmz%2Fwomen_for_women.kmz%3Fa%3Dlarge'
于 2012-08-22T22:37:37.110 に答える
8

Windowsプラットフォームで利用可能

#! python3.6
from urllib.parse import quote


# result: http://www.oschina.net/search?scope=bbs&q=C%E8%AF%AD%E8%A8%80
quote('http://www.oschina.net/search?scope=bbs&q=C语言',safe='/:?=&')
于 2018-01-03T12:32:57.740 に答える
2

urllib.quoteまたはurllib.quote_plusをお探しですか?質問で述べたように、URL文字列全体を引用しないことに注意してください。通常、パス内またはクエリ文字列の後に部分を引用します。アプリケーションで使用するもの。

于 2012-08-22T22:39:23.170 に答える