string find mystery
apt.shansen at gmail.com
Thu Sep 3 07:46:28 CEST 2009
On Wed, Sep 2, 2009 at 10:33 PM, Helvin Lui <helvinlui at gmail.com> wrote:
> Thanks! I just realised that too, but I used the condition: .find() >
> 0 But I think your's is better.
> Simple programming knowledge... > <
Ah, but != 0 vs > 0 isn't a question of better, but correctness: because if
.find() returns 0, that's a successful result. That means it successfully
found the string-- at index 0, meaning the beginning of the string. This is
a function of Python indexing sequences starting with 0. Some people have
argued that this -1 behavior on .find is "unpythonic" from time to time, but
the other solutions just aren't very good for various reasons (e.g.,
An alternate is .index() which raises ValueError on not-found which
side-steps the oddity if the -1.
On the blog:
if (myString.find('bye') != -1):
It's generally bad-form to surround the expression passed to the "if"
statement in parens (unless necessary for implicit line wrapping purposes)
:) It's considered more Pythonic and clear to just do:
if myString.find('bye') != -1:
Although of course, that's a style and preference issue and so it's really
up to you.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list