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>This is just a feature of slicing strings in Python. Notice that</p>

<pre><code>stringvar = 'aaacodebbb'
stringvar[10000:10001]
</code></pre>

<p>returns an empty string value and no error.</p>

<p>However, </p>

<pre><code>stringvar[10000]
</code></pre>

<p><em>will</em> return an error.</p>

<p>As explained in the answer of <a href="http://stackoverflow.com/a/509295/6815126">this question</a>:</p>

<blockquote>
  <p>Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.</p>
</blockquote>

<p>In the examples you've given, having python <em>not</em> return an "index out of range" error is ideal.</p>

python