Python Forum

Full Version: string index out of range
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here is the code that is causing IndexError...

s = "python"
print(s[8])
Output:
Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range
But this code is not occured error!
Could someone tell me why this is happening?


s = "python"
print(s[:8])
Output:
python
Slices are polite?

What would you prefer, for the slice to give you as big a slice as it can, up to what you ask, or to raise an exception. The author picked the former.
(Jan-13-2021, 03:27 AM)deanhystad Wrote: [ -> ]Slices are polite?

What would you prefer, for the slice to give you as big a slice as it can, up to what you ask, or to raise an exception. The author picked the former.

What I want to know is why the error did not occur when the range of the index is greater than the length of the string.
From the python docs

Sequences also support slicing: a[i:j] selects all items with index k such that i <= k < j. When used as an expression, a slice is a sequence of the same type. This implies that the index set is renumbered so that it starts at 0.

So the slice range is a limitation on the index, not a generator of the index. When slicing 'python' the sequences is already limited to indices 0 to 5 because len('python') == 6. The slice will never test for 'python'[8] because 'python'[8] is not part of the 'python' sequence.
I found the following.

From the python intro:
Quote:Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.