帮助str.find
:
>>> print str.find.__doc__
S.find(sub [,start [,end]]) -> int #returns an integer
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
也许你想做这样的事情,解决方案使用str.find
:
cows = "111 cows 222 cows "
start = 0 # search starts from this index
cow = cows.find('cows', start) # find the index of 'cows'
while cow != -1: # loop until cow != -1
startingpos = cow - 4
print(cows[startingpos:cow])
start = cow + 1 # change the value of start to cow + 1
# now search will start from this new index
cow = cows.find('cows', start) #search again
输出:
111
222