URL编码字符串

时间:2015-03-06 01:24:44

标签: python

我可以执行以下操作来构建网址:

base_url = 'http://google.com/'
qs = urllib.urlencode({'q': string})
url = base_url + '?' + qs

有没有办法对字符串进行url编码?例如,我希望能够做到:

url = 'http://google.com/?q=' + urlencode('this is my search'))

1 个答案:

答案 0 :(得分:4)

使用urllib.quoteurllib.quote_plus,例如:

>>> urllib.quote('this is my string')
'this%20is%20my%20string'

>>> urllib.quote_plus('this is my string')
'this+is+my+string'