string.find indexing in Python
<p>I'm trying to understand <strong><em>why</em></strong> the following python code incorrectly returns the string "dining":</p>

<pre><code>def remove(somestring, sub):
"""Return somestring with sub removed."""
    location = somestring.find(sub)
    length = len(sub)
    part_before = somestring[:location]
    part_after = somestring[location + length:]
    return part_before + part_after

print remove('ding', 'do')
</code></pre>

<p>I realize the way to make the code run correctly is to add an if statement so that if the location variable returns a -1 it will simply return the original string (in this case "ding"). The code, for example, should be:</p>

<pre><code>def remove(somestring, sub):
"""Return somestring with sub removed."""
    location = somestring.find(sub)
    if location == -1:
        return somestring
    length = len(sub)
    part_before = somestring[:location]
    part_after = somestring[location + length:]
    return part_before + part_after
print remove('ding', 'do')
</code></pre>

<p>Without using the if statement to fix the function, the part_before variable will return the string "din". I would love to know why this happens. Reading the python documentation on string.find (which is ultimately how part_before is formulated) I see that the location variable would become a -1 because "do" is NOT found. But if the part_before variable holds all letters before the -1 index, shouldn't it be blank and not "din"? What am I missing here?</p>

<p>For reference, Python documentation for string.find states:</p>

<p><code>string.find(s, sub[, start[, end]])</code></p>

<p>Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.</p>