class find_all_low(object):
def __init__(self, string, wanted):
self.forfind = string
self.wanted = wanted
self.appeareList = []
def findonce(self):
return self.forfind.find(self.wanted)
def idx_sum(self,newidx):
return self.appeareList[len(self.appeareList)-1] + newidx + len(self.wanted)
def dofind(self):
while True:
appearance = self.findonce()
if appearance >=0:
self.forfind = self.forfind[appearance+len(self.wanted):]
if not self.appeareList == []:
newidx = appearance
appearance = self.idx_sum(newidx)
self.appeareList.append(appearance)
else:
break
return self.appeareList
string = 'ontheway 123 onmysid 234 no do on 345 on the land of honnor'
stringFind = find_all_low(string, '23')
resultList = stringFind.dofind()
print resultList
for re in range(0,len(resultList)):
print '**'+string[resultList[re]:]+'\n'
python 里的str.find()只能找到最左边出现的第一个字符
这个方法通过反复执行find()方法,找到某字符在一个字符串中所有出现的低位index
结果:
[10, 21]
**23 onmysid 234 no do on 345 on the land of honnor
**234 no do on 345 on the land of honnor