当前位置:  首页>> 技术小册>> Python合辑2-字符串常用方法

21、find()

检测指定内容是否包含在字符串中,如果是返回开始的索引值,否则返回-1。

  1. s = 'Machine Learning'
  2. idx = s.find('a')
  3. print(idx)
  4. print(s[idx:])
  5. # 1
  6. # achine Learning
  7. s = 'Machine Learning'
  8. idx = s.find('aa')
  9. print(idx)
  10. print(s[idx:])
  11. # -1
  12. # g

此外,还可以指定开始的范围。

  1. s = 'Machine Learning'
  2. idx = s.find('a', 2)
  3. print(idx)
  4. print(s[idx:])
  5. # 10
  6. # arning