i am building a URL and rep开发者_运维技巧lacing all the spaces with +
url.replace(' ','+')
for some reason it is not replacing any of the white spaces!
anyone know what is wrong?
The replace function doesn't replace anything in-place - you need to assign it:
url = url.replace(' ','+')
You are probbly still looking at the old url. replace returns new string with replaced values. Try:
url = url.replace(' ', '+')
Aside:
If you are encoding a query or path component for inclusion in a URL, you will need to do more than simply replacing the space character. There are many other characters which won't fit unencoded into a URL component, and which may break the URL if you try. These have to be replaced by %nn
hexadecimal escape sequences.
Use urllib
to take care of URL-encoding rather than trying to do it yourself with string methods. For example:
>>> import urllib
>>> param= 'Hello world!'
>>> url= 'http://www.example.com/script.py?a='+urllib.quote_plus(param)
>>> url
'http://www.example.com/script.py?a=Hello+world%21'
(urllib.quote_plus()
is designed explicitly for form parameters in the query string, so it'll use +
for spaces, as opposed to %20
which urllib.quote()
produces. %20
works in path components as well as query components, so it's a bit safer than +
, but slightly more messy visually.)
If you have more than one parameter, use urlencode()
on a dictionary. This is generally easier to read than trying to stick strings together:
>>> params= {'foo': 'bar', 'bof': 'Hello world!'}
>>> url= 'http://www.example.com/script.py?'+urllib.urlencode(params)
>>> url
'http://www.example.com/script.py?foo=bar&bof=Hello+world%21'
精彩评论