English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
slice()函数返回一个slice对象,该对象可用于对字符串,列表,元组等进行切片。
slice对象用于切片给定的序列(字符串,字节,元组,列表或,
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))
Output result
slice(None, 3, None) slice(1, 5, 2)
在这里,result1和result2是切片对象。
现在我们了解了slice对象,让我们看看如何从slice对象获取子字符串,子列表,子元组等。
# 程序从给定字符串获取子字符串 py_string = 'Python' # stop = 3 # 包含 0, 1 and 2 Index slice_object = slice(3) print(py_string[slice_object]) # Pyt # start = 1, stop = 6, step = 2 # Include 1, 3 and 5 Index slice_object = slice(1, 6, 2) print(py_string[slice_object]) # yhn
Output result
Pyt yhn
py_string = 'Python' # start = -1, stop = -4, step = -1 # Include index -1, -2 and -3 slice_object = slice(-1, -4, -1) print(py_string[slice_object]) # noh
Output result
noh
py_list = ['P', 'y', 't', 'h', 'o', 'n'] py_tuple = ('P', 'y', 't', 'h', 'o', 'n') # Include index 0, 1 and 2 slice_object = slice(3) print(py_list[slice_object]) # ['P', 'y', 't'] # Include index 1 and 3 slice_object = slice(1, 5, 2) print(py_tuple[slice_object]) # ('y', 'h')
Output result
['P', 'y', 't'] ('y', 'h')
py_list = ['P', 'y', 't', 'h', 'o', 'n'] py_tuple = ('P', 'y', 't', 'h', 'o', 'n') # Include index -1, -2 and -3 slice_object = slice(-1, -4, -1) print(py_list[slice_object]) # ['n', 'o', 'h'] # Include index -1 and -3 slice_object = slice(-1, -5, -2) print(py_tuple[slice_object]) # ('n', 'h')
Output result
['n', 'o', 'h'] ('n', 'h')
The slice object can be replaced with Python's index syntax.
You can use the following syntax alternately for slicing:
obj[start:stop:step]
For example,
py_string = 'Python' # Include index 0, 1 and 2 print(py_string[0:3)) # Pyt # Include index 1 and 3 print(py_string[1:5:2)) # yh
Output result
Pyt yh