python小练习-找出字符串中的子字符串

it2022-05-05  39

1 #方法1 2 #找出字符串中以a开头,以b结尾的所有子串 3 def find_substr(string): 4 result = [] 5 for i,s in enumerate(string): 6 for j,e in enumerate(string): 7 if s == 'a' and e == 'b' and j > i: 8 result.append(string[i:j+1]) 9 new_result = set(result) 10 return new_result 1 #方法2 2 def serach_index(target,string): 3 i = 0 4 index = [] 5 for str in string: 6 if str == target: 7 s = string.index(target,i) 8 i = s + 1 9 index.append(s) 10 return index 11 12 def find_str(start_list,end_list,string): 13 result = [] 14 for s in start_list: 15 for e in end_list: 16 if s < e: 17 result.append(string[s:e+1]) 18 new_result = set(result) 19 return new_result 20 21 def findall(string): 22 a = serach_index('a',string) 23 b = serach_index('b',string) 24 return find_str(a,b,string) 1 string = 'aaabbbabab' 2 #调用函数 3 findall(string) 4 5 #或者 6 7 find_substr(string)

 

转载于:https://www.cnblogs.com/sukesaha/p/7682982.html


最新回复(0)