Python slice()函数
Python slice()函数返回一个切片对象。
任何类型的对象序列(字符串、字节、元组、列表或范围)或实现 __getitem__() 和 __len__() 方法的对象,然后可以使用 slice() 方法对该对象进行切片。
Syntax:
- slice(stop)
- slice(start, stop, step)
Parameters:
- start: Starting index where the slicing of object starts.
- stop: Ending index where the slicing of object stops.
- step: It is an optional argument that determines the increment between each index for slicing.
Return Type: Returns a sliced object containing elements in the given range only.
注意:如果只传递了一个参数,那么 start 和 step 被认为是 None。
示例 1: Python切片字符串
Python3
# Python program to demonstrate
# slice() operator
# String slicing
String = 'GeeksforGeeks'
s1 = slice(3)
s2 = slice(1, 5, 2)
print("String slicing")
print(String[s1])
print(String[s2])
Python3
# Python program to demonstrate
# slice() operator
# List slicing
L = [1, 2, 3, 4, 5]
s1 = slice(3)
s2 = slice(1, 5, 2)
print("List slicing")
print(L[s1])
print(L[s2])
Python3
# Python program to demonstrate
# slice() operator
# Tuple slicing
T = (1, 2, 3, 4, 5)
s1 = slice(3)
s2 = slice(1, 5, 2)
print("\nTuple slicing")
print(T[s1])
print(T[s2])
Python3
# Python program to demonstrate
# slice() operator
# String slicing
String = 'GeeksforGeeks'
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print("String slicing")
print(String[s1])
print(String[s2])
# List slicing
L = [1, 2, 3, 4, 5]
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print("\nList slicing")
print(L[s1])
print(L[s2])
# Tuple slicing
T = (1, 2, 3, 4, 5)
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print("\nTuple slicing")
print(T[s1])
print(T[s2])
输出:
String slicing
Gee
ek
示例 2: Python切片列表或Python切片数组
Python3
# Python program to demonstrate
# slice() operator
# List slicing
L = [1, 2, 3, 4, 5]
s1 = slice(3)
s2 = slice(1, 5, 2)
print("List slicing")
print(L[s1])
print(L[s2])
输出:
List slicing
[1, 2, 3]
[2, 4]
示例 3: Python切片元组
Python3
# Python program to demonstrate
# slice() operator
# Tuple slicing
T = (1, 2, 3, 4, 5)
s1 = slice(3)
s2 = slice(1, 5, 2)
print("\nTuple slicing")
print(T[s1])
print(T[s2])
输出:
Tuple slicing
(1, 2, 3)
(2, 4)
负索引
在Python中,负序列索引表示从数组末尾开始的位置。 slice()函数也可以有负值。在这种情况下,迭代将向后执行,即从头到尾。
Python3
# Python program to demonstrate
# slice() operator
# String slicing
String = 'GeeksforGeeks'
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print("String slicing")
print(String[s1])
print(String[s2])
# List slicing
L = [1, 2, 3, 4, 5]
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print("\nList slicing")
print(L[s1])
print(L[s2])
# Tuple slicing
T = (1, 2, 3, 4, 5)
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print("\nTuple slicing")
print(T[s1])
print(T[s2])
输出:
String slicing
GeeksforGe
se
List slicing
[1, 2]
[5, 3]
Tuple slicing
(1, 2)
(5, 3)