內置函數slice()
用於對給定的對象或序列進行切片。序列可以是字符串、字節、元組、列表或範圍。該功能允許指定拼接的開始和結束位置。
**slice(start, stop, step)** #where all parameters should be integers
切片()參數:
取三個參數。如果發出第一個和第三個參數,我們可以將語法寫成 slice(stop)。
參數 | 描述 | 必需/可選 |
---|---|---|
開始 | 對象切片開始的起始整數。如果未提供,默認為無 | 可選擇的 |
停止 | 整數,直到切片發生。切片在索引 stop -1(最後一個元素)處停止 | 需要 |
步驟 | 整數值,確定切片的每個索引之間的增量。如果未提供,則默認為無。 | 可選擇的 |
切片()返回值
這個返回切片對象包含指定範圍內的一組索引。
| 投入 | 返回值 |
| If 參數 | 切片對象 |
Python 中slice()
方法的示例
示例 1:如何創建切片對象進行切片
# contains indices (0, 1, 2)
result1 = slice(3)
print(result1)
# contains indices (1, 3)
result2 = slice(1, 5, 2)
print(slice(1, 5, 2))
輸出:
slice(None, 3, None)
slice(1, 5, 2)
示例 2:如何使用切片對象獲取子串
# Program to get a substring from the given string
py_string = 'Python'
# stop = 3
# contains 0, 1 and 2 indices
slice_object = slice(3)
print(py_string[slice_object]) # Pyt
# start = 1, stop = 6, step = 2
# contains 1, 3 and 5 indices
slice_object = slice(1, 6, 2)
print(py_string[slice_object]) # yhn
輸出:
Pyt
yhn
示例 3:如何獲取子列表和子元組
py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')
# contains indices 0, 1 and 2
slice_object = slice(3)
print(py_list[slice_object]) # ['P', 'y', 't']
# contains indices 1 and 3
slice_object = slice(1, 5, 2)
print(py_tuple[slice_object]) # ('y', 'h')
輸出:
['P', 'y', 't']
('y', 'h')
示例 4:如何使用負索引獲取子列表和子元組
py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')
# contains indices -1, -2 and -3
slice_object = slice(-1, -4, -1)
print(py_list[slice_object]) # ['n', 'o', 'h']
# contains indices -1 and -3
slice_object = slice(-1, -5, -2)
print(py_tuple[slice_object]) # ('n', 'h')
輸出:
['n', 'o', 'h']
('n', 'h')
示例 5:如何使用索引語法進行切片
py_string = 'Python'
# contains indices 0, 1 and 2
print(py_string[0:3]) # Pyt
# contains indices 1 and 3
print(py_string[1:5:2]) # yh
輸出:
Pyt
yh
原創文章,作者:T1C94,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/128610.html