我需要分享这样的链接
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'
关于python - 将字符串转换为有效的 url 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21208040/