python find 返回元素的索引

 

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
1

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')
2

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', 3)
4

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', 1, 2)
-1

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. 

 

posted @ 2018-12-18 12:45  anobscureretreat  阅读(564)  评论(0编辑  收藏  举报