tags:

views:

64

answers:

3

i am building a URL and replacing all the spaces with +

url.replace(' ','+')

for some reason it is not replacing any of the white spaces!

anyone know what is wrong?

+4  A: 

The replace function doesn't replace anything in-place - you need to assign it:

url = url.replace(' ','+')
Graeme Perrow
That is because string is immutable. If you have many changes to strings it is useful to make them lists by list(mystring) to avoid too much copying.
Tony Veijalainen
tony, can you elaborate please on what you just said
I__
+2  A: 

You are probbly still looking at the old url. replace returns new string with replaced values. Try:

url = url.replace(' ', '+')
gruszczy
A: 

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'
bobince