python中的find、rfind、index、rindex

find()從左向右尋找子序列的位置,如存在多個相同子序列只返回第一個查找到的位置,若是子序列不存在返回-1spa

rfind()從右向左尋找子序列的位置.....code

index()從左向右尋找子序列的位置,若是子序列不存在報錯,因此通常咱們用find()更好一些blog

rindex()從右向左尋找子序列的位置.....string

舉個列子:ast

1 a = "hello world"
2 a1 = a.find("l")
3 a2 = a.rfind("v")
4 print(a1)
5 print(a2)

輸出結果:class

2
-1

 

1 b = "hello world"
2 b1 = b.index("l")
3 b2 = b.rindex("v")
4 print(b1)
5 print(b2)

輸出結果:module

Traceback (most recent call last):
  File "lianxi.py", line 3, in <module>
    b2 = b.index("v")
ValueError: substring not found

使用方式如代碼書寫call

相關文章
相關標籤/搜索