string index out of range error in for loop
<p>I am trying to make a program that searches a string for 'bob' and prints the amount of times it appears.
Here is the code:</p>

<pre><code>s = 'mbobobboobooboo'
numbob = 0
for i in range(len(s) ) :
    u = s[i] 
    if u == 'o':
        g = i
        if g != 0 and g != len(s) :
            if (s[g+1]) == 'b' and (s[g-1]) == 'b': #this line is the problam
                numbob += 1
                print("Number of times bob occurs is: " +str(numbob) )
</code></pre>

<p>I am getting the string index out of range error and i cant seem to fix it. any suggestions</p>

<p>When you make your condition :</p>

<pre><code>if (s[g+1]) == 'b' and (s[g-1]) == 'b':
</code></pre>

<p>At the last element of your string, it is impossible to do <code>s[g+1]</code> because it is out of the string.</p>

<p>So you have to finish your loop just before the end. Like this for exemple :</p>

<pre><code>for i in range(len(s)-1) :
</code></pre>

python python-3.x