函數原型:find(str, startIndex, endIndex)
調用形式:Str.find(str,startIndex,endIndex)
解釋:
Str:源字符串
str:想要查找的“字符串”。—— 目標字符串
startIndex:查找的首字母位置(從0開始計數。默認:0)
endIndex: 查找的末尾位置(默認-1)
返回值:如果查到:返回第一個出現的位置。否則,返回-1。
例如,
Str="hello world!,hello world!"
str1="llo"
index=Str.find(str1)
index的值是2。
所以find()函數就是在源字符串(Str)中查找第一個與目標字符串(str1)一致的子串(x)。然后返回這個子串(x)的第一個字符(‘l’)在源字符串中的下標位置。
要想查找所有符合的子串的位置呢
def find_all(Str,str1):
index_list = []
index = Str.find(str1,0,-1)
while index != -1:
index_list.append(index)
index = Str.find(str1,index+len(str1),-1)
return index_list if len(index_list) > 0 else -1