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. 

 

相关文章:

  • 2021-11-09
  • 2021-10-28
  • 2021-12-19
  • 2021-12-12
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-22
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2021-06-14
  • 2021-11-05
  • 2022-01-23
相关资源
相似解决方案