[Tutor] format string

Kent Johnson kent37 at tds.net
Wed Jul 19 15:58:31 CEST 2006


devayani barve wrote:
> Hi
>  
> This is my program:
>
> import urllib
> ans='y'
> while ans=='y':   
>     name=raw_input("Enter search:")
>     name=name.replace(' ','+')
>     name=name.replace('&','%26')
>     go_url=" http://www.google.co.in/search?hl=en&q=%s 
> <http://www.google.co.in/search?hl=en&q=%s>" %name+"&meta=lr\%3Dlang_en"
>     print go_url
>     page = urllib.urlopen(go_url).read()
>     ans=raw_input("do you want to continue?: ")
>
> It gives following error: 
>
> Traceback (most recent call last):
>   File "C:\python\urllib.py", line 1, in -toplevel-
>     import urllib
>   File "C:\python\urllib.py", line 9, in -toplevel-
>     page = urllib.urlopen(go_url).read()
> AttributeError: 'module' object has no attribute 'urlopen'
>  
> What does it mean?
Your program is called urllib.py, when you import urllib you are 
importing your own program. Call the program something else (and delete 
C:\python\urllib.pyc) and it should work better.
> also I tried to assign go_url as
>  
>     
> go_url="http://www.google.co.in/search?hl=en&q=%s&meta=lr\%3Dlang_en 
> <http://www.google.co.in/search?hl=en&q=%s&meta=lr%5C%3Dlang_en>" %name
>  
> It takes the % in "%3D" as a part of  format is there a way I 
> can overcome this retaining the same manner of assinging?
If you want a literal % in a format string you have to escape it with 
another %, in other words use %% to get a single literal escape.

Kent




More information about the Tutor mailing list