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>Use </p>

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

<p>or</p>

<pre><code>g!=len(s)-1
</code></pre>

<p><code>len()</code> gives you the total number of characters, which will be the index of the character after the last one since indexing starts at 0.</p>

<p>You can get rid of the <code>if g!=0 and g!=len(s)</code> part all together if you use </p>

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

python python-3.x