python find 返回元素的索引

时间:2021-07-11 00:11:50

As it turns out, there is a string method named find that is remarkably similar to the function we wrote:

>>> word = 'banana'
>>> index = word.find('a')
>>> index

In this example, we invoke find on word and pass the letter we are looking for as a param- eter.

Actually, the find method is more general than our function; it can find substrings, not just characters:

>>> word.find('na')

By default, find starts at the beginning of the string, but it can take a second argument, the index where it should start:

>>> word.find('na', )

This is an example of an optional argument; find can also take a third argument, the index where it should stop:

>>> name = 'bob'
>>> name.find('b', , )
-

This search fails because b does not appear in the index range from 1 to 2, not including 2. Searching up to, but not including, the second index makes find consistent with the slice operator.