切片(Slice)是一个取部分元素的操作,是Python中特有的功能。它可以操作list、tuple、字符串。
Python的切片非常灵活,一行代码就可以实现很多行循环才能完成的操作。切片操作的三个参数 [start: stop: step] ,其中start是切片的起始位置,stop是切片的结束位置(不包括),step可以不提供,默认值是1,并且step可为负数(详细使用见下)
下面盘点下切片的常见操作。
1

切取的元素不包括右端点

2
切片左端点为0,可省略

3
每两个取一个

4
支持倒数切片,倒数第一个元素的索引是-1

5
原样复制一个list

6
起始索引和终止索引都省略,也就都为默认值,如下步长设置为2切取元素

7
一行代码实现列表反转

8
步长为负数,实际上指明了一个逆向迭代器。如下逆向倒数,每两个取一个。

9
值得注意,Python超出索引范围不报错

10
步长step为0,会报错

11
切片操作的三个参数可以用表达式

12
连续切片操作

13
元组对象的切片操作

14
字符串的切片

以上就是Python切片常用的14个操作,希望能帮助到大家。
转自:Python中14个切片操作,你常用哪几个?