shouldn't 'string'.find('ugh') return 0, not -1 ?
Tim Chase
python.list at tim.thechases.com
Wed Oct 31 11:55:50 EDT 2007
> Well, I this is another idiom in itself, right?
> Your checking if something is part of an iterable.
> I'm checking truth before entering a conditional expression.
I'm not sure I follow. I simply replaced your
if check.find('something')
with
if 'something' in check:
which (1) is more readable (2) is more pythonic (especially as I
understand that find() is going away), and (3) works like I
understand you want from your description.
For strings, they're the same behavior. However, it also works
for testing membership in other container classes (sets, lists,
tuples, dicts, etc).
Your original code's behavior would be analog to
if not check.startswith('something')
which is not at all what I think you meant. This
misinterpretation alone is reason enough to give the find()
method the boot.
> The latter is considered to be pythonic, right?
Clarity is pythonic. The find() call returns an offset, or -1 if
not found (because the beginning-of-string is offset=0). It
would also make sense if this returned None instead of -1.
Either way, find() should be used for returning index values. If
you're testing for the presence of a substring, use the
if 'something' in check:
to do the test. And as for the start/end parameters to find,
they are interpreted as slice endpoints, so
if check.find('something', start) != -1:
would be the same as
if 'something' in check[start:]:
and
if check.find('something', start, end) != -1:
would be the same as
if 'something' in check[start:end]:
both of which are far more readable than their find() variants.
Hope this helps clarify,
-tkc
More information about the Python-list
mailing list