I was reading python cookbook and came upon this recipe:
If you have a slice instance s, you can get more information about it by looking at its
s.start, s.stop, and s.step attributes, respectively. For example:
>>> a = slice(5, 50, 2)
>>> a.start
5
>>> a.stop
50
>>> a.step
2
>>>
In addition, you can map a slice onto a sequence of a specific size by using its indi ces(size) method. This returns a tuple (start, stop, step) where all values have been suitably limited to fit within bounds (as to avoid IndexError exceptions when indexing). For example:
>>> s = 'HelloWorld'
>>> a.indices(len(s))
(5, 10, 2)
>>> for i in range(*a.indices(len(s))):
... print(s[i])
...
W
r
d
I looked up indices() method in Python official documentation but couldn't find it. Is the book making a mistake here? If not, what does this method do?
Calling help(a) on your initialized slice object, I found the following -
| indices(...)
| S.indices(len) -> (start, stop, stride)
|
| Assuming a sequence of length len, calculate the start and stop
| indices, and the stride length of the extended slice described by
| S. Out of bounds indices are clipped in a manner consistent with the
| handling of normal slices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With