如何使用python将url字符串转换为安全字符?

2024-05-29 04:48:48 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下字符串:

"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中,最好的方法是什么?


Tags: 模块方法函数字符串comhttpurlfor
3条回答

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='/:?=&')

你在找urllib.quote还是urllib.quote_plus?请注意,您没有引用问题中提到的整个url字符串。通常在路径中或查询字符串之后引用该部分。无论你要在申请中使用哪一个。

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'

相关问题 更多 >

    热门问题