Getting an IndexError: string index out of range
<p>I'm not sure why I'm getting an </p>

<blockquote>
  <p>IndexError: string index out of range </p>
</blockquote>

<p>with this code. </p>

<pre><code>s = 'oobbobobo'
a = 0
for b in range(len(s)-1):
    if (s[b] == 'b') and (s[b+1] == 'o') and (s[b+2] == s[b]):
        a += 1
    elif (s[b] == 'b') and (s[b+1] == 'o') and None:
        break 

print("Number of times bob occurs is: ", a)
</code></pre>

<p>I thought the <code>elif</code> statement would fix the error, so I'm lost.</p>

<p>In this case, the length of <code>s</code> is 9 which means that you're looping over <code>range(8)</code> and therefore the highest value that <code>b</code> will have is <code>7</code> (Stay with me, I'm going somewhere with this ...)</p>

<p>When <code>b = 7</code> (on the last iteration of the loop), the conditional expression in the <code>if</code> statement is being checked which contains:</p>

<pre><code>(s[b+2] == s[b])
</code></pre>

<p>Well, since <code>b = 7</code>, <code>b + 2 = 9</code>, but <code>s[9]</code> will be out of bounds (remember, python is 0 indexed so the highest index in a a string of length <code>9</code> is <code>8</code>).</p>

<p>I'm guessing that the fix is to just modify the <code>range</code> statement:</p>

<pre><code>for b in range(len(s)-2):
    ...
</code></pre>

python