Python:继续 For 循环中的下一个字母

Python: Moving on to the next letter on For Loop

如何在第一次迭代完成之前继续 for 循环中的下一个字母?

s = 'mmmmbobob'
for letter in s:
    if letter is 'b':   
        s = s + 1 <<<<<<<<<RIGHT HERE<<<<<<<<<
            if letter is 'o':
                s = s + 1 <<<<<<<<<THEN HERE<<<<<<<<< 
                    if letter is "b":
                        counter_bob += 1
                    else:
                        break
                else:
                    break
            else:
                continue      
print('Number of times bob occurs is: %d' % (bob_name_counter))

目前,您正在尝试将 1 添加到字符串 s,这将引发 TypeError。即使 s 一个 int,以这种方式递增它也不会移动到 Python(或任何语言)循环的下一次迭代我知道)。

您可以使用关键字continue 立即移动到循环的下一次迭代。此处的文档:https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

但是,我不认为这正是您想在此处执行的操作,因为看起来您正在尝试计算主字符串 s 中子字符串 'bob' 的出现次数.

相反,您应该遍历 s 字符的索引,并在每个点检查当前字符和接下来的两个字符是否一起构成子字符串 'bob'。如果这样增加 counter_bob.

考虑到这一点的代码重构示例:

s = 'mmmmbobob'
counter_bob = 0

for i in range(len(s)):
    if s[i:i+3] == 'bob':
        counter_bob += 1

print('Number of times bob occurs is: %d' % (counter_bob))

打印:

Number of times bob occurs is: 2