for循环中find()的行为

2024-06-25 22:35:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始从头学习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为什么在第二个循环中它变成了8,而不是2


Tags: 方法字符串intarget目标forindexhere
1条回答
网友
1楼 · 发布于 2024-06-25 22:35:07

看看这个例子,看看string.find是如何工作的 https://www.geeksforgeeks.org/python-string-find/

但要回答你的问题, 第1次迭代:

 ->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

第二次迭代:

 ->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

等等

相关问题 更多 >