参数形式
- slice(stop)
- slice(start, stop[, step])
Manual
Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.
直译
返回一个由range(start, stop, step)指定的索引集的切片对象,start和step参数默认为None。切片对象的只读数据属性start、stop和step仅返回参数值(或它们的默认值),无论它们是用于Numerical Python和其他第三方扩展,它们都没有其他明确的功能。当使用扩展索引语法时也能生成切片对象,例如:a[start:stop:step]或a[start:stop, i]。对于其代替版本—itertools.islice()则可以返回一个迭代器。
实例
>>> s = slice(1, 3)
>>> s
slice(1, 3, None)
>>> a[s]
[2, 3]
>>> s = slice(None,None,-1)
>>> 'Hello world!'[s]
'!dlrow olleH'
Note
实际编程中我还是更喜欢使用使用索引切片,相对简洁,很少能想起来还有slice()这个函数,但两者总体使用效果相同,例如:
>>> 'Hello world!'[2:4]
'll
>>> 'Hello world!'[::2]
'Hlowrd'
>>> 'Hello world!'[::-1]
'!dlrow olleH'
>>> [1, 2, 3, 7, 9][1:3]
[2, 3]