首页 > 解决方案 > for 循环中 find() 的行为

问题描述

我刚开始从头开始学习 python,我有一个与 find() 方法相关的问题。

这是打印字符串中目标索引的练习的简化版本。

phrase = 'Here, there, everywhere!'
index = 0
target = 'ere'
for n in (0, 1, 2):
index = phrase.find(target, index + 1)
        print(index)

Output:
   1
   8
   20

我一步一步地运行了这个,虽然结果满足了练习,但我特别不理解这部分,index = phrase.find(target, index + 1)因为如果index = 0在开始时然后在循环内部,它会得到index + 1为什么在第二个 cicle 中它变成了8而不是2?

标签: python

解决方案


Take a look at this example to see how string.find works https://www.geeksforgeeks.org/python-string-find/

But to answer your question, 1st iteration:

 ->phrase.find(target, index + 1) is looking for the string "ere" in the string "ere, there, everywhere!"
 ->it see that the first instance of "ere" occurs are index starting at 1
 ->phrase.find() thus returns 1
 ->index=1 now

2nd iteration:

 ->phrase.find(target, index + 1) is phrase.find(target, 2)

 ->Thus its looking for the string "ere" in the string "re, there, everywhere!"
 ->The 1st instance of "ere" can now be found starting at index 8
-> Thus you print out 8

and so on....


推荐阅读