前言
我們知道,字符串內置了很多功能的處理函數,其中,find、index函數都可以接受一個參數意義是作為目標子串,而返回母串中從左到右遍歷時子串第一次出現的索引值(每一次調用都是從頭開始,沒有記憶),如果查詢不到返回-1。
如下面的例子:
如果,子串不在母串中出現,則find函數返回-1,而index方法返回ValueError錯誤,這也是兩者的區別,接上例:
深入
rindex rfind函數:功能類似,把母串從右向左遍歷,找到子串第一次出現的位置,也沒有記憶性。
后續
我編寫了一個函數,實現find函數類似的功能,但是這次要把所有的子串位置以列表形式返回,這是函數的功能。
1 # coding=utf-8 2 def find_all(source,dest): 3 length1,length2 = len(source),len(dest) 4 dest_list = [] 5 temp_list = [] 6 if length1 < length2: 7 return -1 8 i = 0 9 while i <= length1-length2: 10 if source[i] == dest[0]: 11 dest_list.append(i) 12 i += 1 13 if dest_list == []: 14 return -1 15 for x in dest_list: 16 print("Now x is:%d. Slice string is :%s"% (x,repr(source[x:x+length2])),end=" ") 17 if source[x:x+length2] != dest: 18 print(" dest != slice") 19 temp_list.append(x) 20 else: 21 print(" dest == slice") 22 for x in temp_list: 23 dest_list.remove(x) 24 return dest_list 25 26 s1="He!wworld!www.baidu.cowws.cowwppww" 27 s2="ww" 28 index_list = find_all(s1,s2) 29 if index_list != -1: 30 print("Now dest_list is:{}".format(index_list)) 31 else: 32 print("Error finding!")