假设我有以下字符串:

"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中执行此操作的最佳方法是什么?

最佳答案

Python 2的urllib.quote_plus和Python 3的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'

10-07 13:43