[Tutor] Problem with strings

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Thu, 17 Aug 2000 12:00:33 -0700 (PDT)


On Thu, 17 Aug 2000, Daniel D. Laskey, CPA wrote:

Hello!  Let's take a look at the error message:


> 	if 'Totals for 4I' in line:
[omitted code]
> Error message:
> Traceback (innermost last):
>   File "today4.py", line 15, in ?
>     if 'Totals for 4I' in line:
> TypeError: string member test needs char left operand


This requires a little explanation on that error message: the 'if/in' will
look through each element in 'line', seeing if it matches up with 'Totals
for 4I'.  The problem is that 'line' is a sequence of letters, so this
search will compare against every single _letter_.  That's why it's
saying that weird 'member test needs char left operand'.  The same error
occurs if you try something like:

###
>>> 'monkey' in 'this is a zoo of animals'
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: string member test needs char left operand
>>> 't' in 'this is a zoo of animals'
1
>>> 'x' in 'this is a zoo of animals'
0
###


What you had above, then, could be translated as:

  if ('Totals for 4I' == line[0] or
      'Totals for 4I' == line[1] or ...)

So it doesn't quite work.


In this case, you'll want to use the string finding routine,
string.find().  It will search for a sub-string within a larger string,
and will return the position where it finds it.  If it can't find it,
it'll return -1.  Here's a sample of it in action:

###
>>> string.find('this is an alphabeta word', 'alphabeta')
11
>>> string.find('bonobos are indigenous', 'mammal')
-1
###


Be careful --- I often accidently reverse the order of the arguments.