[Tutor] (no subject)

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 6 Apr 2001 03:19:46 -0700 (PDT)


On Fri, 6 Apr 2001, wong chow cheok wrote:

> hai chow cheok here again. this is a program i wrote
> 
> import re
> import urllib
> import sys
> import string
> 
> name={'AS':'Alor Setar '}
> if sys.argv[1]==["upper()"]:
>     p=re.compile('min:\s\s\d\d\s.^*', re.IGNORECASE)
>     q=re.compile('max:\s\s\d\d\s.^*', re.IGNORECASE)
>     a=re.compile('whole day^*|morning^*|afternoon^*|evening^*', 
> re.IGNORECASE)
>     b=re.compile('fcastimg/(.*?).gif^*', re.IGNORECASE)
>     
> html=urllib.urlopen("http://www.kjc.gov.my/cgi-bin/fcastdisplay.cgi?lang=EN&loc="+sys.argv[1]).read()
>     mintemp=p.search(html)
>     maxtemp=q.search(html)
>     time=a.search(html)
>     con=b.search(html)
>     print 'Temperature for ',name[sys.argv[1]], mintemp.group(),'and ', 
> maxtemp.group()
>     print 'Weather for the day is ',con.groups(1)[0],'in the ', time.group()
> 
> else:
>     print 'all caps'
> 

> what i want to do is to make sure my argument variable is in caps. if it is 
> not it will return an error message. for example when i type in


One way to check if something is in capitals is to compare a particular
string with its capitalized form.  In Python 2.0, we can write the
following code:

###
>>> mailing_list = 'tutor@python.org'
>>> if mailing_list.upper() == mailing_list:
...     print 'ok'
... else:
...     print 'all caps'
...
all caps
>>> shouting = 'TUTOR@PYTHON.ORG'
>>> if shouting.upper() == shouting:
...     print 'ok'
... else:
...     print 'all caps'
...
ok
###

If you're using Python 1.52, the function string.upper() will also work to
convert a string to all caps.



> also is there anyway to make sure i don't type the wrong argument variable. 
> for example if i type
> 
> python weather USA, it is caps but out of my range. a few pointers would be 
> great.

Sure!  If the search is unsuccessful, the search()ing function of your
regular expressions will return the None value to show that it wasn't able
to find anything.  

    http://python.org/doc/current/lib/Contents_of_Module_re.html

mentions this briefly.


With this, we can check for these missing values in several ways:

    if mintemp == None or maxtemp == None or time == None or con == None:
        ...

is one way to do it.  However, there's a nice Python idiom to say this:

    if None in [mintemp, maxtemp, time, con]:
        ...

Hope this helps!