Bizarre behavior of the 'find' method of strings

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Aug 10 22:56:43 EDT 2011


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.

Your subject line says:

Bizarre behavior of the 'find' method of strings

What makes you think this is a problem with the find method?

As a programmer, you should be able to isolate where the problem *actually*
occurs:

>>> a = 'popular'
>>> a.find('o')
1
>>> a.find('a')
5

So there is no problem with the find method: it correctly finds the index
(starting at zero, not one) of the first (going left-to-right) matching
substring.

Now, if you take a slice, you get an unexpected (to you) result:

>>> a[1:5]
'opul'

It doesn't matter where the 1 and 5 come from. The slice can't tell that
they were the output of find, or how they were generated:

>>> a[1000-999:20/4]
'opul'

Now that you have isolated the actual problem, you can ask a better
question:

"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



-- 
Steven




More information about the Python-list mailing list