字符串、列表、元组(tuple)在python中都符合“序列”这一特征,符合“序列”特征的对象都可以使用切片(slice)去访问它们的任意部分,切片操作符在python中的原型是:
[start:stop:step], 表示为[开始索引:结束索引:步长]
- 开始索引:从0开始,序列从左向右累增计数,最一个值的索引记为-1;
- 结束索引:切片操作到此为止,不包含该索引的值;
- 步长:步长表示切片的间隔,默认步长为1,如果步长为负数,则表示从右向左取,步长不能为0;
常规切片操作
>>> L = ['A','B','C','D','E']
>>> L[::]
['A','B','C','D','E']
>>> L[0:-1:1]
['A','B','C','D']
>>> L[0:5]
['A','B','C','D','E']
>>> L[::2]
['A','C','E']
>>> L[0:100:2]
['A','C','E']
>>> L[::-1]
['E','D','C','B','A']
>>> L[4:0:-1]
['E','D','C','B']
>>> L[:]
['A','B','C','D','E']
>>> L[-3:-1]
['C','D']
>>> L[-3:]
['C','D','E']
使用切片操作对列表插入和修改元素
>>> L = ['A','B','C','D','E']
>>> L[2:0] = ['F']
['A','B','F','C','D','E']
>>> L = ['A','B','C','D','E']
>>> L[2:1]=['F']
['A','B','F','C','D','E']
>>> L = ['A','B','C','D','E']
>>> L[2:2]=['F']
['A','B','F','C','D','E']
>>> L = ['A','B','C','D','E']
>>> L[2:3]=['F']
['A','B','F','D','E']
>>> L = ['A','B','C','D','E']
>>> L[2:4]=['F']
['A','B','F','E']
>>> L = ['A','B','C','D','E']
>>> L[2:5]=['F']
['A','B','F']
删除切片
>>> L = ['A','B','C','D','E']
>>> del L[2:2]
['A','B','C','D','E']
>>> L = ['A','B','C','D','E']
>>> del L[2:3]
['A','B','D','E']
>>> L = ['A','B','C','D','E']
>>> del L[2:-1]
['A','B','E']
>>> L = ['A','B','C','D','E']
>>> del L[2:]
['A','B']
面对大河我无限惭愧
我年华虚度 空有一身疲倦
和所有以梦为马的诗人一样
岁月易逝 一滴不剩