Bug in string.find; was: Re: Proposed PEP: New style indexing, was Re: Bug in slice type

Bryan Olson fakeaddress at nowhere.org
Sat Aug 27 04:08:47 EDT 2005


Steve Holden wrote:
 > Bryan Olson wrote:
 >> [...] I see no good reason for the following
 >> to happily print 'y'.
 >>
 >>      s = 'buggy'
 >>      print s[s.find('w')]
 >>
 >>  > Before using the result you always have to perform
 >>  > a test to discriminate between the found and not found cases. So I
 >> don't
 >>  > really see why this wart has put such a bug up your ass.
 >>
 >> The bug that got me was what a slice object reports as the
 >> 'stop' bound when the step is negative and the slice includes
 >> index 0. Took me hours to figure out why my code was failing.
 >>
 >> The double-meaning of -1, as both an exclusive stopping bound
 >> and an alias for the highest valid index, is just plain whacked.
 >> Unfortunately, as negative indexes are currently handled, there
 >> is no it-just-works value that slice could return.
 >>
 >>
 > If you want an exception from your code when 'w' isn't in the string you
 > should consider using index() rather than find.

That misses the point. The code is a hypothetical example of
what a novice or imperfect Pythoners might have to deal with.
The exception isn't really wanted; it's just vastly superior to
silently returning a nonsensical value.


 > Otherwise, whatever find() returns you will have to have an "if" in
 > there to handle the not-found case.
 >
 > This just sounds like whining to me. If you want to catch errors, use a
 > function that will raise an exception rather than relying on the
 > invalidity of the result.

I suppose if you ignore the real problems and the proposed
solution, it might sound a lot like whining.


-- 
--Bryan



More information about the Python-list mailing list