slice()
Published Sep 26, 2024
Contribute to Docs
In Python, the slice()
function is used to create a slice object, which can then be applied to a sequence (e.g., a string, tuple, list, etc.).
Syntax
slice(start, stop, step)
start
: This optional integer indicates where the slicing begins. The default value is0
if not provided.stop
: This integer indicates up to where the slicing takes place. It stops at indexstop-1
(the last element of the sequence).step
: This optional integer specifies the increment between each index for slicing. The default value is1
if not provided.
Example
The following example shows the use of the slice()
function:
# Create a tuple with some values in itfruits = ("Apple", "Banana", "Orange", "Kiwi", "Strawberry", "Plum", "Watermelon")# Create a slice objecta = slice(3)# Return the resultant slice objectprint(fruits[a])
The output of the code is as follows:
('Apple', 'Banana', 'Orange')
Codebyte Example
The following codebyte example demonstrates how the slice()
function is used to create a slice object, which is then applied to the string to extract specific portions based on the defined ranges:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.