[Tutor] script error question [checking for substrings]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon Dec 16 01:06:00 2002


On Mon, 16 Dec 2002, Kirk Bailey wrote:

> Folks, I get this error when examining a string for the presence of a smaller
> string:
>
> Traceback (innermost last):
>    File "/www/www.tinylist.org/cgi-bin/TLlistkill2.py", line 187, in ?
>      if mylist not in aliasline:	# if this is NOT the alias to remove,
> TypeError: string member test needs char left operand

Hi Kirk,


I think you're misusing 'in'.  It scans well as an English sentence, but
it isn't doing what you think it's doing in Python:

###
>>> def vowel(character):
...     return character in 'aeiou'
...
>>> vowel('a')
1
>>> vowel('z')
0
>>>
>>> 'hello' in 'hello world'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'in <string>' requires character as left operand
###


'in' is meant to see if some element is within a collection.  It's
commonly used when we're checking for an element in a list, but it also
works on strings.  But when we're doing 'in' in a string, we're checking
to see if a single character is 'in' a string, and that's has a different
meaning from seeing if a word lies within --- is a "substring" --- of the
larger string.


Instead of 'in', you'll probably want to use the 'find()' method, which
tells us exactly the position where the smaller string starts to occurs.
And if the smaller "substring" isn't part of the larger string, the find()
method will return -1:

###
>>> 'hello world'.find('world')
6
>>> 'hello world'.find('hello')
0
>>> 'hello world'.find('goodbye')
-1
###



Given this, we can write a quicky wrapper to make it easier to check for
substrings:

###
>>> def isSubstring(smaller, larger):
...     return larger.find(smaller) != -1
...
>>> isSubstring('hello', 'hello world')
1
>>> isSubstring('goodbye', 'hello world')
0
###


Hope this helps!