Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
string index out of range
#1
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
Reply
#2
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.
Reply
#3
(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.
Reply
#4
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.
Reply
#5
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Thumbs Down I hate "List index out of range" Melen 20 3,154 May-14-2023, 06:43 AM
Last Post: deanhystad
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 5,954 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  IndexError: list index out of range dolac 4 1,843 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  I'm getting a String index out of range error debian77 7 2,277 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,408 May-03-2022, 01:39 PM
Last Post: Anldra12
  matplotlib x axis range goes over the set range Pedroski55 5 3,101 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  IndexError: list index out of range rf_kartal 6 2,759 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,233 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav
  IndexError: list index out of range Laplace12 1 2,186 Jun-22-2021, 10:47 AM
Last Post: Yoriz
  IndexError: list index out of range brunolelli 11 6,340 Mar-25-2021, 11:36 PM
Last Post: brunolelli

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020