0

How can I move on to the next letter in a for loop before 1st iteration finishes?

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))
Henry Woody
  • 14,024
  • 7
  • 39
  • 56
Doug1982
  • 13
  • 1
  • 2

1 Answers1

0

Currently, you're trying to add 1 to the string s, which will throw a TypeError. Even if s was an int, incrementing it in this fashion would not move to the next iteration of the loop in Python (or any language I know).

You can use the keyword continue to move to the next iteration of a loop immediately. Docs here: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

However, I don't think that is exactly what you want to do here, since it looks like you are trying to count the occurrences of the substring 'bob' in your main string s.

Instead you should iterate over the indices of the characters of s and at each point check if the current character and next two together form the substring 'bob'. If so increment counter_bob.

An example refactor of your code with this in mind:

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

Which prints:

Number of times bob occurs is: 2
Henry Woody
  • 14,024
  • 7
  • 39
  • 56