Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串转换为有效的url内容_Python_Url_Parameters - Fatal编程技术网

Python 将字符串转换为有效的url内容

Python 将字符串转换为有效的url内容,python,url,parameters,Python,Url,Parameters,我需要分享这样的链接 mysite.com?url=https://anothersite.com&text=some text mysite.com?url=https%3A%2F%anothersite.com&text=some%20text 所以一定是这样 mysite.com?url=https://anothersite.com&text=some text mysite.com?url=https%3A%2F%anothersite.com&t

我需要分享这样的链接

mysite.com?url=https://anothersite.com&text=some text
mysite.com?url=https%3A%2F%anothersite.com&text=some%20text
所以一定是这样

mysite.com?url=https://anothersite.com&text=some text
mysite.com?url=https%3A%2F%anothersite.com&text=some%20text
我可以用这种方法得到它

def URL():
    try:
        text = 'some text'
        url = 'anothersite.com'
        parameters = 'url=%s&text=%s' % (url , text)
        for r,n in [(':','%3A') , (' ','%20') , ('/','%2F')]:
            parameters = parameters.replace(r,n)
        return 'mysite.com?%s' % parameters
    except Exception as e:
       print '%s (%s)' % (e.message, type(e))
       return ""
它可以工作,但我必须指定每个字符,因此如果我的文本有一个“#”,我必须将,(“#,'%23')添加到我的列表中

有没有解决这个问题的好方法?

使用和
str.index
拆分字符串(如果需要拆分):


您可能对
safe
kwarg to
urllib.parse.quote
感兴趣:

qs = 'mysite.com?url=https://anothersite.com&text=some text'

urllib.parse.quote(qs,safe='=?&')
Out[10]: 'mysite.com?url=https%3A%2F%2Fanothersite.com&text=some%20text'
从文档中:

RFC2396统一资源标识符(URI):通用语法列出 以下是保留字符

保留=“;”|“/”|“?”|“:“|“@”|“&”|“=”|“+”| “$”|“,”

在上面的保留字符中,您似乎希望在查询字符串中保持
=?&
不转义,请告诉它。它会逃过剩下的