Python Gotcha's?

Chris Angelico rosuav at gmail.com
Thu Apr 5 19:00:37 EDT 2012


On Fri, Apr 6, 2012 at 4:10 AM, Jon Clements <joncle at googlemail.com> wrote:
> One I've had to debug...
>
>>>> text = 'abcdef'
>
>>>> if text.find('abc'):
>        print 'found it!'
> # Nothing prints as bool(0) is False
>
>>>> if text.find('bob'):
>        print 'found it!'
> found it!
>
> Someone new who hasn't read the docs might try this, but then I guess it's not really a gotcha if they haven't bothered doing that.

But your original will actually never work, since find() returns -1 if
not found. This one is far more a gotcha in PHP, where the equivalent
function returns boolean False if not found, or index (starting from
0) if found. Returning -1 on not-found is far more logical. (Plus, of
course, the 'substring in string' syntax exists for just testing.)

ChrisA



More information about the Python-list mailing list