我已经远远超出了我的编码类(class),所以我知道的知识比开始学期时要求的要多一些。 编辑请原谅定义函数的缩进错误。
编辑暂时删除。非常感谢你们的反馈。我会暂时把它放回去。
最佳答案
您可以改用 while
循环,其条件与 if
语句中的中断条件相反。如果循环完成且没有中断,索引 position
将等于上限 needle_characters
,因此使用 position ==needle_characters
作为等效条件原始 for
循环的 else
子句。
更改:
for position in range(needle_characters):
if haystack[counter+position] != needle[position]:
break
else:
return counter
至:
position = 0
while position < needle_characters and haystack[counter+position] == needle[position]:
position += 1
if position == needle_characters:
return counter
关于python - 我可以在 if 语句中不使用 break 来执行此操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55426875/