Understanding index out of range Python
<p>Hello thanks in advance.</p>

<p>i can get my code to work but i need help understanding what the problem is.</p>

<p>i am doing a test questions on codingbat and came across this one.</p>

<p>Return the number of times that the string "code" appears anywhere in the given string, accept any letter for the 'd', so "cope" and "cooe" count.</p>

<blockquote>
  <p>count_code('aaacodebbb') â 1 count_code('codexxcode') â 2
  count_code('cozexxcope') â 2</p>
</blockquote>

<p>now after a few tries i got my code to work </p>

<blockquote>
<pre><code>def count_code(str):
    count =0
    for i in range(len(str)):
        if str[i:i+2] == 'co' and str[i+3:i+4]=='e':
            count += 1
    return count
print(count_code('codecodecode'))
</code></pre>
</blockquote>

<p>^ I understand this (and I could have done regular expressions but i can not import) </p>

<p>But my first attempt was this:</p>

<blockquote>
<pre><code>def count_code(str):
    count =0
    for i in range(len(str)):
       if str[i:i+2] == 'co' and str[i+3]=='e':
        count += 1
    return count
print(count_code('codecodecode'))
</code></pre>
</blockquote>

<p>the browser (the browser saves, compiles, and runs) gave me an index out of range error and after testing i understand why.  when i = 9 ... i +9 = 12 which is longer than the string so out of range i get it.  But i ran the 2nd code in Aptana and it worked fine   so is the second bad code or not? </p>

<p>but the code that works containing str[i+3:i+4] == 'e' does not go out of range and i do not understand why.  when i reaches counter 9 then it would be str[12:13] which is longer than the string.  </p>

<p>thanks for the help still learning basics and want to make sure i have a good foundation.</p>

<p>When you say <code>mystring[x:y]</code>, that is called <em>slicing</em>, which has built-in bounds checking.</p>

<p>But a plain list index such as <code>mystring[99]</code> does not have built-in bounds checking, so you get an <code>IndexError</code>.</p>

python