Python Slice Example | slice() Method Tutorial
Python Slice Example | slice() Method Tutorial is today’s topic. The slice() constructor creates the slice object representing the set of indices specified by range(start, stop, step). The slice object is used to determine how to slice the sequence.
You can specify where to start the slicing, and where to end. You can also determine the step, which allows you to, e.g., slice only every other item.
Python Slice Example
The slice object is used to slice the given sequences like string, bytes, tuple, list, range or any object which supports the sequence protocol ( which implements __getitem__() and __len__() method).
The syntax of Python slice() function is following.
slice(stop) slice(start, stop, step)
The start parameter is optional, and it is the starting integer where the slicing of the object starts.
The stop parameter is required, and it is an integer number specifying at which position to end the slicing.
The step parameter is optional, and it is an integer value which determines the increment between each index for slicing.
Let’s see the example of Python slice() method.
# app.py A = ('Bad Bunny', 'Louis Fonsi', 'Daddy Yankee', 'Drake') result = slice(1,3) print(A[result])
The output of the above program is following.
See in the above example, we have sliced the A object from the index 1 to 3, and we get the elements like Louis Fonsi and Daddy Yankee.
Get substring from a given string using slice object
Let’s see the following example of String where we will get a substring from a string.
# app.py A = 'AppDividend' result = slice(3) print(A[result])
Now, see the output below.
Slice String Using Negative Index
In the following example, we will slice a string based on the negative index.
# app.py A = 'AppDividend' result = slice(-3, -1) print(A[result])
In the below example, we have passed the negative index which means that the execution starts from the end and then go forward and return the value. See the output below.
Finally, Python Slice Example | slice() Method Tutorial is over.