I don't quite get this "string".find()

Tim Peters tim.peters at gmail.com
Thu Nov 11 14:57:12 EST 2004


[Jaime Wyant]
> Will someone explain this to me?
>
> >>> "test".find("")
> 0
>
> Why is the empty string found at position 0?

Because index 0 is the smallest index at which "" is found:

>>> "test"[0:0] == ""
True

As a string method, find() acts like this (skipping obfuscating optimizations):

    def find(haystack, needle):
        for i in range(len(haystack)):
            if haystack[i : i+len(needle)] == needle:
                return i
        return -1



More information about the Python-list mailing list