[Python-3000] Droping find/rfind?
Josiah Carlson
jcarlson at uci.edu
Wed Aug 23 20:52:54 CEST 2006
"Steven Bethard" <steven.bethard at gmail.com> wrote:
>
> On 8/23/06, Barry Warsaw <barry at python.org> wrote:
> > I agree with Tim -- if we have to get rid of one of them, let's get
> > rid of index/rindex and keep find/rfind. Catching the exception is
> > much less convenient than testing for -1.
>
> Could you post a simple example or two? I keep imagining things like::
>
> index = text.index(...)
> if 0 <= index:
> ... do something with index ...
> else:
> ...
A more-often-used style is...
index = text.find(...)
if index >= 0:
...
Compare this with the use of index:
try:
index = text.index(...)
except ValueError:
pass
else:
...
or even
index = 0
while 1:
index = text.find(..., index)
if index == -1:
break
...
compared with
index = 0
while 1:
try:
index = text.index(..., index)
except ValueError:
break
...
> try:
> index = text.index(...)
> ... do something with index ...
> except ValueError:
> ...
In these not uncommon cases, the use of str.index and having to catch
ValueError is cumbersome (in terms of typing, indentation, etc.), and is
about as susceptible to bugs as str.find, which you have shown by
putting "... do something with index ..." in the try clause, rather than
the else clause.
- Josiah
More information about the Python-3000
mailing list