If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.
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). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.
让我们检查一下slicing works:
所以
[-1:1:-1]
意味着i = -1
,j = 1
,k = -1
。你知道吗i
是负数,所以i = -1
表示i = len(s) + (-1) = len(s) - 1
。len(s)
是5
,因此我们得到以下切片:"loops"[4:1:-1]
。你知道吗根据上面的定义,我们现在使用以下索引来定义项:
4
,4 - 1 = 3
,4 - 2 = 2
。我们停在4 - 3 = 1
因为那是我们的终点,我们不包括这一点。你知道吗所以结果是索引
4, 3, 2
,也就是'spo'
。你知道吗最后,该字符串被
2
相乘,后者重复一次:'spospo'
。你知道吗相关问题 更多 >
编程相关推荐