Python slice() 函式



**Python slice() 函式**返回一個切片物件,可用於切片序列,例如列表、元組、字串等。此函式有助於執行多個操作,包括從給定字串中查詢子字串以及從集合中提取子部分。

**slice()** 函式是內建函式之一,通常用於切片序列。切片一詞定義為提取指定序列物件某一部分的過程。

語法

以下是 Python **slice()** 函式的語法 -

slice(start, end, step)

引數

Python **slice()** 函式接受三個引數,所有引數都是可選的 -

  • **start** - 此引數接受一個整數值,表示我們需要開始切片的起始位置。其預設值為 0。

  • **end** - 它也接受一個整數值,表示切片的結束位置。

  • **step** - 它指定切片索引之間所需的增量。預設值為 1。

返回值

Python **slice()** 函式返回一個新的切片物件。

slice() 函式示例

練習以下示例以瞭解如何在 Python 中使用 **slice()** 函式

示例:slice() 函式的使用

以下示例顯示了 Python slice() 函式的使用。在這裡,我們定義一個字串並嘗試使用 slice() 函式提取其子字串。

orgnlStr = "Simply Easy Learning Tutorials Point"
subStr = orgnlStr[slice(21, 36)]
print("Printing the sub-string of the given string:", subStr)

當我們執行上述程式時,它會產生以下結果 -

Printing the sub-string of the given string: Tutorials Point

示例:使用 slice() 函式切片列表

可以透過傳遞 start、end 和 step 引數來進行切片,這允許使用者以特定的增量從起始索引到結束索引獲取列表的一部分。在下面的程式碼中,我們以 2 個位置的增量訪問列表的第二個索引到第六個索引的元素。

orgnList = [22, 44, 66, 88, 108, 118]
newSlicedList = orgnList[slice(2, 6, 2)]
print("Printing the newly sliced list:", newSlicedList)

以下是上述程式碼的輸出 -

Printing the newly sliced list: [66, 108]

示例:使用 slice() 函式切片元組

由於元組也是一個序列物件,因此我們可以像在下面的程式碼中所示那樣對元組使用 slice() 函式。

orgnlTup = ("Simply", "Easy", "Learning", "Tutorials", "Point")
newSlicedTup = orgnlTup[slice(0, 3)]
print("Printing the newly sliced tuple:")
print(newSlicedTup)

上述程式碼的輸出如下 -

Printing the newly sliced tuple:
('Simply', 'Easy', 'Learning')

示例:使用 slice() 函式進行負切片

如果我們將負索引號傳遞給 slice() 函式,則索引將從序列的末尾開始計數,這允許我們以相反的順序切片序列。以下程式碼說明了如何反轉給定字串。

orgnlStr = "TutorialsPoint"
newRevStr = orgnlStr[slice(None, None, -1)]
print("Printing the string in reverse order:")
print(newRevStr)

以下是上述程式碼的輸出 -

Printing the string in reverse order:
tnioPslairotuT
python_built_in_functions.htm
廣告