Python Forum
string index out of range - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: string index out of range (/thread-31972.html)



string index out of range - jade_kim - Jan-13-2021

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



RE: string index out of range - deanhystad - Jan-13-2021

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.


RE: string index out of range - jade_kim - Jan-13-2021

(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.


RE: string index out of range - deanhystad - Jan-13-2021

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.


RE: string index out of range - jade_kim - Jan-13-2021

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.