0

I have just started learning python and I was playing with the slice (:) operator and strings. For some reason if I specify an invalid index followed by the slice operator it does not give the "Out of range" error.

>>> s='Hello'
>>> print s[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

>>> print s[5:]
//Prints just a newline, no error

Can someone please explain why I am not getting error in the 2nd case.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Pratt
  • 851
  • 2
  • 10
  • 16

1 Answers1

7

From the documentation on slicing:

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.

In other words: the index can be too big but in that case it's replaced by the string size.

Note that your string s has five characters so s[5:] is the same as calling s[len(s):] which is the same as getting an empty string (as the missing upper bound defaults to len(s) as well, so it ultimately becomes s[len(s):len(s)]).

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180