Counting matching substrings in a string
<pre><code>s = "abobabobabob"
total = 0

for i in range(len(s)):
    if s[i-1 : i+2] == 'bob':
        total += 1

print ('times bob occurs is:' + str(total))
</code></pre>

<p>Is there a simpler way to change the <code>if</code> statement? Also, could someone tell me what <code>i-1 : i+2</code> does?</p>

<p>I wrote this code to find the occurrences of "bob" and I am stuck for a while.</p>

<p>if s[i-1 : i+2] == 'bob' is checking whether the current index -1 to current index + 2 is 'bob'. It will cause issue, since i begin at 0 and i-1 is the last element of list<br></p>

<p>try:</p>

<pre><code>s = "abobabobabob"
total = 0

for i in range(1,len(s)):
    if s[i-1 : i+2] == 'bob':
        total += 1
</code></pre>

<p>there is a better way in two line</p>

<pre><code>s= "abobabobabob"
print sum(  s[i:i+3] =='bob' for i in range(len(s)-2) )

3
</code></pre>

python