shouldn't 'string'.find('ugh') return 0, not -1 ?
jelle feringa
jelleferinga at gmail.com
Wed Oct 31 12:17:23 EDT 2007
More information about the Python-list mailing list
Wed Oct 31 12:17:23 EDT 2007
- Previous message (by thread): shouldn't 'string'.find('ugh') return 0, not -1 ?
- Next message (by thread): shouldn't 'string'.find('ugh') return 0, not -1 ?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Thanks for your in-depth explanation Tim. Which is impossible to disagree with! On 10/31/07, Tim Chase <python.list at tim.thechases.com> wrote: > > > 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 > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20071031/fc7977c3/attachment.html>
- Previous message (by thread): shouldn't 'string'.find('ugh') return 0, not -1 ?
- Next message (by thread): shouldn't 'string'.find('ugh') return 0, not -1 ?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list