[Tutor] find is confusing..?
Kirby Urner
urnerk@qwest.net
Tue, 25 Jun 2002 21:55:46 -0700
Some languages have such an operator, e.g. in xBase we say
"str"$"string"
to get a boolean T or F (just let us know if it's in there, we don't
care where exactly).
To actually get the position of a substring, we'd use:
pos = AT("str","string")
-- and here, since indexing is 1-based instead of 0-based, returning
0 means "not found". (pos would be 1 after the above).
But I can well understand a design philosophy that says "if you go
to all the trouble to ascertain whether a substring is contained in a
string, it's wasteful to just say 'yes', as you've obviously done the
work to also know the starting position". To have find() return 0 or 1
is actually withholding information which the computer must have.
find() has the ability to come up empty handed (-1) whereas index()
is a command to return an index, so it's designed to really signal
a problem (returns an exception) if, in fact, there is no such index.
The intent is you shouldn't be asking for the index unless you know
it's there; use find() if you're not so sure (but either way, if it's there,
you get the starting position without any further instructions, which
is getting a full return for your clock cycles (imagine running find on
a string of 10000 characters and just getting back 1 for true, and
then needing to start over with index() to get the position -- that'd be
frustratingly redundant).
It's very easy to package either index() or find() to make new
functions that work however you like though.
Kirby
At 10:08 PM 6/25/2002 -0400, Andrei Kulakov wrote:
>Hello snake eaters..
>
>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,
>and false if it wasn't, and you'd use index() to find the position,
>which would return -1 if it wasn't found?
>
>The reason I ask is that I thought.. maybe there's a good reason for
>this that I'm missing. Is there?
>
>Thanks,
>
> - Andrei