Skip to main content
 首页 » 编程设计

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

2024年11月01日26Terrylee

我需要分享这样的链接

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') 添加到我的列表中。

有什么好的方法可以解决吗?

请您参考如下方法:

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

link = 'mysite.com?url=https://anothersite.com&text=some text' 
 
>>> link[:link.index('=')] + '=' + urllib.quote(link[link.index('=')+1:]) 
'mysite.com?url=https%3A//anothersite.com%26text%3Dsome%20text'