string find mystery

Stephen Hansen apt.shansen at gmail.com
Thu Sep 3 01:46:28 EDT 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.,
returning None).

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.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090902/d08a6c76/attachment.html>


More information about the Python-list mailing list