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>Using <code>enumerate()</code></p>

<pre><code>s = "abobabobabob"
n = len([i for i, w in enumerate(s) if s[i:i+3] == "bob"])

print ('times bob occurs is:', n)
</code></pre>

<p>This checks for every character in string <code>s</code>(by index <code>i</code>) if the character + two characters on the right equals "bob".</p>

<hr>

<p>About your secundary question: </p>

<p>In your example:</p>

<pre><code>s[i-1 : i+2]
</code></pre>

<p>refers to the index (<code>i</code>) of the characters in the string, where <code>s[0]</code> is the first character, while <code>s[i-1 : i+2]</code> is a <em>slice</em> of the string <code>s</code>, from the current character <code>-1</code> (the one on the left) to the current character <code>+2</code> (the second character on the right).</p>

python