English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
slice()函数返回一个slice对象,该对象可用于对字符串,列表,元组等进行切片。
slice对象用于切片给定的序列(字符串,字节,元组,列表或范围)或任何支持序列协议的对象(实现__getitem__()和__len__()方法)。
slice()的语法为:
slice(start, stop, step)
slice() 可以采用三个参数:
start(可选) -对象切片开始的起始整数。如果未提供,则默认为None。
stop-整数,直到切片发生。切片在索引stop-1(最后一个元素)处停止。
step(可选) -整数值,用于确定切片时每个索引之间的增量。如果未提供,则默认为None。
# 包含索引 (0, 1, 2) result1 = slice(3) print(result1) # 包含索引 (1, 3) result2 = slice(1, 5, 2) print(slice(1, 5, 2))
Ausgabenergebnis
slice(None, 3, None) slice(1, 5, 2)
在这里,result1和result2是切片对象。
现在我们了解了slice对象,让我们看看如何从slice对象获取子字符串,子列表,子元组等。
# 程序从给定字符串获取子字符串 py_string = 'Python' # stop = 3 # 包含 0, 1 und 2 Index slice_object = slice(3) print(py_string[slice_object]) # Pyt # start = 1, stop = 6, step = 2 # enthalten 1, 3 und 5 Index slice_object = slice(1, 6, 2) print(py_string[slice_object]) # yhn
Ausgabenergebnis
Pyt yhn
py_string = 'Python' # start = -1, stop = -4, step = -1 # enthalten Index -1, -2 und -3 slice_object = slice(-1, -4, -1) print(py_string[slice_object]) # noh
Ausgabenergebnis
noh
py_list = ['P', 'y', 't', 'h', 'o', 'n'] py_tuple = ('P', 'y', 't', 'h', 'o', 'n') # enthalten Index 0, 1 und 2 slice_object = slice(3) print(py_list[slice_object]) # ['P', 'y', 't'] # enthalten Index 1 und 3 slice_object = slice(1, 5, 2) print(py_tuple[slice_object]) # ('y', 'h')
Ausgabenergebnis
['P', 'y', 't'] ('y', 'h')
py_list = ['P', 'y', 't', 'h', 'o', 'n'] py_tuple = ('P', 'y', 't', 'h', 'o', 'n') # enthalten Index -1, -2 und -3 slice_object = slice(-1, -4, -1) print(py_list[slice_object]) # ['n', 'o', 'h'] # enthalten Index -1 und -3 slice_object = slice(-1, -5, -2) print(py_tuple[slice_object]) # ('n', 'h')
Ausgabenergebnis
['n', 'o', 'h'] ('n', 'h')
Slice-Objekte können durch das Index-Syntax in Python ersetzt werden.
Sie können die folgenden Syntaxen zur Schaltung wechseln:
obj[start:stop:step]
Zum Beispiel,
py_string = 'Python' # enthalten Index 0, 1 und 2 print(py_string[0:3)) # Pyt # enthalten Index 1 und 3 print(py_string[1:5:2)) # yh
Ausgabenergebnis
Pyt yh