Why does substring slicing with index out of range work?

前端 未结 3 1236
栀梦
栀梦 2020-11-22 02:32

Why doesn\'t \'example\'[999:9999] result in error? Since \'example\'[9] does, what is the motivation behind it?

From this behavior I can a

3条回答
  •  逝去的感伤
    2020-11-22 03:23

    For the sake of adding an answer that points to a robust section in the documentation:

    Given a slice expression like s[i:j:k],

    The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater

    if you write s[999:9999], python is returning s[len(s):len(s)] since len(s) < 999 and your step is positive (1 -- the default).

提交回复
热议问题