python - 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
?
解决方案
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....
推荐阅读
- selenium - 如何通过 Selenium 从 GUI 自动化的角度处理频繁的应用程序更改
- python - 如何使用 Python 和正则表达式替换符号之间的一组字母
- c++ - 如何恢复ffmpeg streamer网络断开一段时间但最终恢复
- javascript - 如何引用动态创建的元素?
- javascript - 数据可以在 HTML 中访问,但不能在 JavaScript 中访问
- security - 远程服务器上的 msfconsole
- google-apps-script - 创建一个表单,允许您选择要在哪些工作表中运行宏
- javascript - 如何复制具有值的表单
- c - printf("%f") 或 printf("%lf") 用于 c 中的双打?
- prometheus - 在 peometheus 查询中忽略 old 系列