Python 内建函数 - slice(stop)

本文介绍了Python的内建函数slice,它用于创建表示索引范围的对象。slice可以接受start、stop和step参数,默认start为None。切片对象包含只读属性start、stop和step。通常在编程中,人们更倾向于直接使用索引切片语法,如a[start:stop:step],尽管slice()函数提供了相同的功能。此外,文章还提到了与之相关的itertools.islice()函数,它返回一个迭代器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参数形式

  • 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)指定的索引集的切片对象,startstep参数默认为None。切片对象的只读数据属性startstopstep仅返回参数值(或它们的默认值),无论它们是用于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]

拓展阅读

itertools.islice()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值