[Python-ideas] Deprecate str.find

Nick Coghlan ncoghlan at gmail.com
Sat Jul 16 10:50:12 CEST 2011


On Fri, Jul 15, 2011 at 11:57 PM, 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.

As others have noted, the typical usage pattern of:

idx = s.find(sub)
if idx >= 0:
   # do something that needs idx

is nice and clean and significantly faster than searching the string
twice. Universally discouraging find() in favour of index() is
questionable, as the above is significantly cleaner than the index
based alternative.

So, I have a different suggestion (that actually paves the way for the
eventual deprecation of find()):

    Update str.index() to accept an optional sentinel value.

If the sentinel argument is not supplied, then a missing substring
raises ValueError as it does now. If it is supplied, then a missing
substring returns the sentinel value instead of throwing an exception.
The above idiom could then be expressed cleanly as:

idx = s.index(sub, missing=None)
if idx is not None:
   # do something that needs idx

However, this seemingly simple suggestion is complicated by the fact
that string methods do not currently accept keyword arguments and
index() already accepts two optional positional arguments (for
substring searching).

Perhaps the more general solution of try/except/value expressions is
worth reconsidering.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list