[Tutor] find('') returns 0

eryksun eryksun at gmail.com
Mon Sep 17 02:33:32 CEST 2012


On Sun, Sep 16, 2012 at 7:51 PM, Don Jennings <dfjennings at gmail.com> wrote:
> This behavior seems strange to me:  the find method of a string returns the position zero when you search for an empty string (granted, I can't quite figure out why you'd search for an empty string, either).
>
>>>> 'abc'.find('')
> 0
>
> Anyone care to share a good explantion for this behavior and possible use cases? Thanks!

It actually returns the value of "start":

    >>> 'abc'.find('', 0)
    0
    >>> 'abc'.find('', 1)
    1
    >>> 'abc'.find('', 2)
    2

It's looking for the length 0 substring ''. So it will match a 0
length slice at the given start position:

    >>> 'abc'[0:0]
    ''
    >>> 'abc'[1:1]
    ''
    >>> 'abc'[2:2]
    ''

When you find 'b', for example, it searches for a length 1 slice:

    >>> 'abc'.find('b')
    1
    >>> 'abc'[1:2]
    'b'

The 'in' operator also searches for a substring:

    >>> '' in 'abc'
    True


More information about the Tutor mailing list