此代码只是在另一个字符串中查找一个字符串,并返回搜索字符串中出现的最后一个位置,如果未找到则返回 -1。
我不明白为什么我的变量next_y
没有更新,因为它pos
是计算的输入next_y
。我的想法是,如果我更新,pos
那么next_y
也应该更新。取而代之pos
的是更新并永远保持在循环中。
def find_last(x,y):
if x.find(y) == -1:
return -1
pos = x.find(y)
next_y = x.find(y, pos + 1)
while next_y != -1:
pos = pos + next_y
return pos
search = 'tom ran up but tom fell down'
target = 'tom'
print(find_last(search,target))