shouldn't 'string'.find('ugh') return 0, not -1 ?

Carsten Haese carsten at uniqsys.com
Wed Oct 31 10:25:02 EDT 2007


On Wed, 2007-10-31 at 13:31 +0000, jelle wrote:
> the subject pretty much says it all.
> if I check a string for for a substring, and this substring isn't found, 
> should't the .find method return 0 rather than -1?
> this breaks the 
> 
> if check.find('something'):
>     do(somethingElse)
> 
> idiom, which is a bit of a pity I think.

You're using the wrong tool for the job. You only care *whether* the
substring is in the string, but you're asking *where* it is, so you have
to do extra work to translate the answer you get into the answer you
need.

To ask the right question in the first place, use "in" or "not in":

if 'something' in check:
    do(somethingElse)

Also, if string.find returned 0 to say "substring not found", what
should it return for "spam salad".find("spam")?

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list