Strings comparison

Bjorn Pettersen BPettersen at NAREX.com
Mon Dec 30 13:11:15 EST 2002


> From: Dusausoy Bruno [mailto:bruno.dusausoy at skynet.be] 
> 
> Hi,
> 
> I have a problem with strings comparison.
> I've pasted the example of the getopt module and I've removed 
> the long options because I don't need them. But when I run 
> it, Python gives me errors:
> 
> ./test.py -h
> Traceback (most recent call last):
>   File "./test.py", line 24, in ?
>     main()
>   File "./test.py", line 16, in main
>     if o in ("-h"):
> TypeError: 'in <string>' requires character as left operand
> 
[...]
>     opts, args = getopt.getopt(sys.argv[1:], "ho:")
>     for o, a in opts:
>         if o in ("-h"):
[...]
> 
> I'm sure I've made a string comparison mistake but I don't 
> know which one. Can someone help me ?

The if statement should read:

  if o in ("-h",):  # the added comma makes it a one-item tuple

The way you have it, it's interpreted as:

  if o in "-h":

where the 'in' operator currently requires a character on the left hand
side when the right hand side is a string (thus the TypeError you're
seeing). IIUC, Python 2.3 will change the semantics of 'in' to mean
substring containment, so your  code would work then -- but for the
wrong reasons <wink>.

hth,
-- bjorn




More information about the Python-list mailing list