Bizarre behavior of the 'find' method of strings

MRAB python at mrabarnett.plus.com
Thu Aug 11 03:48:35 CEST 2011


On 11/08/2011 02:24, 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.
>
Python uses half-open ranges, which means that the start position is
inclusive and the end position is exclusive.

This means that a[i:j] returns the string starting at position i and
extending upto, but excluding, position j.

The reason that Python uses half-open ranges is that experience (with
the language Mesa) has shown that it results in fewer programming
errors that the alternatives.



More information about the Python-list mailing list