此代碼只是在另一個字符串中查找字符串,並返回搜索字符串中最後一個出現位置,如果未找到,則返回-1。Python while循環 - 變量不更新?
我不明白爲什麼我的變量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))
不,這個假設是不正確的:「我的想法是,如果我更新'pos',那麼'next_y'也應該更新。您需要明確指定爲'next_y',即'next_y = <在此處插入內容>' –
x.find()返回一個數字,它是運行時的計算結果。如果你想再次計算這個值,你需要再次調用它。 – lolopop