[Tutor] find is confusing..?

alan.gauld@bt.com alan.gauld@bt.com
Wed, 26 Jun 2002 11:34:17 +0100


> I just realized that "string".find('str') is very counter-intuitive.. 
> 
> if "string".find("str"):
>     print "found str!" # won't work
> 
> Wouldn't it be much nicer if find returned true if something 
> was found,

No, coz find is not a boolean expression.
What might be better is if strings had an 'includes' operator so 
your code becomes:

if "string".includes('str'):
    print 'contains "str"'

and find() continues to return the index as it currently does 
- which seems like what I'd want from a find command.

You could of course extend string (userstring?) to have an 
includes() method...

> The reason I ask is that I thought.. maybe there's a good reason for
> this that I'm missing. Is there?

Coz if you want to extract the search string its more convenient 
to fetch the index via the find(). Using find then index would be 
slow unless find set an internal state variable used by index but 
then we increase the size of every string...

but using

if "str".find('foo') >= 0:
   print 'found'

doesn't seem too unintuitive to me...

Alan G.