Python slice() 内置函数
来自 Python 3 文档
返回一个表示由 range(start, stop, step) 指定的索引集的 slice 对象。start 和 step 参数默认为 None。Slice 对象具有只读数据属性 start, stop, 和 step,它们仅返回参数值(或其默认值)。
简介
Python 中的 slice() 函数返回一个 slice 对象,可用于对列表、元组或字符串等序列进行切片。slice 对象表示由 start、stop 和 step 指定的一组索引。
示例
furniture = ['table', 'chair', 'rack', 'shelf']
print(furniture[0:4])
print(furniture[1:3])
print(furniture[0:-1])
print(furniture[:2])
print(furniture[1:])
print(furniture[:])
['table', 'chair', 'rack', 'shelf']
['chair', 'rack']
['table', 'chair', 'rack']
['table', 'chair']
['chair', 'rack', 'shelf']
['table', 'chair', 'rack', 'shelf']
对完整列表进行切片将执行复制操作:
spam = ['cat', 'bat', 'rat', 'elephant']
spam2 = spam[:]
print(spam2)
spam.append('dog')
print(spam)
print(spam2)
['cat', 'bat', 'rat', 'elephant']
['cat', 'bat', 'rat', 'elephant', 'dog']
['cat', 'bat', 'rat', 'elephant']