Skip to content Skip to sidebar Skip to footer

Using Slice Operator [:] On Python String Do Not Cause Out Of Bound Error

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

Solution 1:

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)]).

Post a Comment for "Using Slice Operator [:] On Python String Do Not Cause Out Of Bound Error"