Bizarre behavior of the 'find' method of strings

Chris Rebert clp2 at rebertia.com
Wed Aug 10 23:49:49 EDT 2011


On Wed, Aug 10, 2011 at 7:56 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Thu, 11 Aug 2011 11:24 am Jim wrote:
>
>> Greetings, folks,
>>
>> I am using python 2.7.2. Here is something I got:
>>>>> a = 'popular'
>>>>> i = a.find('o')
>>>>> j = a.find('a')
>>>>> a[i:j]
>> 'opul'
>>
>> Well, I expected a[i:j] to be 'opula', and can't think of any reason why
>> this is not happening. So, can anybody help me out about this? Thank you
>> very much.
<snip>
> "Why does slicing not work the way I expect?"
>
> Answer: because Python uses half-open slices, where the end parameter is not
> included. The reason for that is that experience with other languages shows
> that it leads to fewer "off-by-one" errors.
>
> See also:
>
> http://mail.python.org/pipermail/tutor/2010-December/080592.html
> http://en.wikipedia.org/wiki/Off-by-one_error

And further:
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html

Cheers,
Chris



More information about the Python-list mailing list