The slice() function in Python prints a slice object, which can be a string, byte, tuple, list, and range. With this function, you can specify the start and endpoints and even the step to cut.
Basically, this function's job is to take the elements in an array of the original list and create a new list.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Python function queries.
In this context, we shall look into how to use the slice() function in Python.
The slice() function prints out a slice object.
Here, You can specify the start and endpoints and even the step to cut.
It's syntax is given below:
slice(start, stop, step)
slice() can take three parameters:
slice() returns a slice object.
Note: We can use slice with any object which supports sequence protocol (implements __getitem__() and __len()__ method).
1. Let's take a quick look at the below slice() function:
a = ("b", "c", "d", "e", "f", "g", "h")
x = slice(3)
print(a[x])
It's Output would be:
(‘b’, ‘c’, ‘d’)
2. slice() function has a start and endpoint:
a = ("b", "c", "d", "e", "f", "g", "h")
x = slice(3,6)
print(a[x])
The Output will be:
(‘e’, ‘f’, ‘g’)
3. slice() function has a start, endpoint and step is 2
a = ("b", "c", "d", "e", "f", "g", "h")
x = slice(0,6,2)
print(a[x])
It's Output will be:
(‘b’, ‘d’, ‘f’)
4. Get substring using slice object:
# 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
The output will be:
Pyt
yhn
This article covers how to use the slice() function in Python. In fact, the slice() function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).
Example of slice() function in Python:
text = 'Python Programing'
# get slice object to slice Python
sliced_text = slice(6)
print(text[sliced_text])
The will be Output:
Python