[Python-ideas] Deprecate str.find
Mike Graham
mikegraham at gmail.com
Fri Jul 15 15:57:35 CEST 2011
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
More information about the Python-ideas
mailing list