[Python-ideas] Deprecate str.find

Guido van Rossum guido at python.org
Fri Jul 15 16:57:24 CEST 2011


However, in many cases absence of the string is not an error -- you
just need to do something else. So in cases where *if* it's found you
need the position, and *if* it isn't found you need to do something
else, you'd have to use a try/except block to catch the non-error that
is absence. All in all I don't see enough reason to start deprecating
find. But perhaps popular lint-like programs could flag likely abuses
of find?

--Guido

On Fri, Jul 15, 2011 at 6:57 AM, Mike Graham <mikegraham at gmail.com> wrote:
> str.find (and bytes.find) is worse than the alternatives in every way.
> It should be explicitly deprecated in favour of str.__contains__ and
> str.index.
>
> str.find when used to check for substring is inferior to the in
> operator. "if sub in s:" is shorter, easier-to-read, and more
> efficient than "if s.find(sub) != -1:" and is not prone to the error
> "if s.find(sub):" I have occasionally seen.
>
> str.index is better for finding indices in that it supports an
> idiomatic exception-based API rather than a return-code API. Every
> usage of str.find should look like "index = s.find(sub); if index ==
> -1: (exception code)", which is an antipattern in Python. This problem
> is compounded by the fact that the returned value is actually a valid
> value; consider s = 'bar'--s[s.find('x')] is somewhat surprisingly
> 'r'.
>
> Additionally, the existence of str.find violates the
> there's-one-way-to-do-it principle.
>
>
> Mike
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list