我在Python官方文档中找不到的方法
我正在阅读 python 食谱并发现了这个食谱:
如果你有一个切片的实例s,你可以通过查看其获得更多的信息
s.start,s.stop和s.step属性,分别。例如:
>>> a = slice(5, 50, 2)
>>> a.start
5
>>> a.stop
50
>>> a.step
2
>>>
此外,您可以使用其 indices(size) 方法将切片映射到特定大小的序列。这将返回一个元组(开始、停止、步骤),其中所有值都被适当地限制在范围内(以避免索引时出现 IndexError 异常)。例如:
>>> s = 'HelloWorld'
>>> a.indices(len(s))
(5, 10, 2)
>>> for i in range(*a.indices(len(s))):
... print(s[i])
...
W
r
d
我indices()在 Python 官方文档中查找了方法,但找不到。这本书在这里出错了吗?如果不是,这个方法有什么作用?
回答
调用help(a)您初始化的切片对象,我发现了以下内容 -
| 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.