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>The following code searches for the beginning index of each <code>'bob'</code> substring, and adds that value to an array. The <code>total</code> variable just returns the count of the values in that array. </p>

<p><strong>As a one-liner:</strong></p>

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

total = len([i for i in range(len(s)) if s.find('bob', i) == i])

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

<p><strong>Prints:</strong></p>

<pre><code>times bob occurs is: 3
</code></pre>

<p><strong><em>--- Here is an alternative if you want a modification to your <code>for</code> loop:</em></strong></p>

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

for i in range(len(s)):
    if (s.find('bob', i) == i):
        total += 1

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

<p><strong>Prints:</strong></p>

<pre><code>times bob occurs is: 3
</code></pre>

python