ItsMyCode |
The slice()
in Python is a built-in function that returns a slice object and slices any sequence such as string , tuple , list , bytes, range.
slice() Syntax
The syntax of the slice()
is:
**slice(start, stop, step)**
slice() Parameters
The slice()
method can take three parameters.
-
start (optional) – Starting integer where the slicing of the object starts. If omitted, defaults to
None
. - stop – Ending index where the slicing of object stops. The slicing stops at index stop -1 (last element).
-
step (optional) – An optional argument determines the increment between each index for slicing. If omitted, defaults to
None
.
Note: If only one parameter is passed, then both start and step will default to None
.
slice() Return Value
The slice()
method returns a sliced object containing elements in the given range.
Note : We can use slice with any object which supports sequence protocol which means an object that implements __getitem__ ()
and __len()__
method.
*Example 1: * Python slice string Get substring using slice object
# Python program to demonstrate slice() operator
# String slicing
str = 'ItsMyPythonCode'
s1 = slice(3)
s2 = slice(5, 11,1)
print(str[s1])
print(str[s2])
Output
Its
Python
Example 2: Get substring using negative index
In Python, negative sequence indexes represent positions from the end of the array. The slice()
function can take negative values, and in the case of a negative index, the iteration starts from end
to start
.
# Python program to demonstrate slice() operator
# String slicing
str = 'ItsMyPythonCode'
s1 = slice(-4)
s2 = slice(-5, -11,-1)
print(str[s1])
print(str[s2])
Output
ItsMyPython
nohtyP
Example 3: Python slice list or Python slice array
# Python program to demonstrate slice() operator
# List slicing
lst = [1, 2, 3, 4, 5]
s1 = slice(3)
s2 = slice(1, 5, 2)
print(lst[s1])
print(lst[s2])
# Negative list slicing
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print(lst[s1])
print(lst[s2])
Output
[1, 2, 3]
[2, 4]
[1, 2]
[5, 3]
*Example 4: * Python slice tuple
# Python program to demonstrate slice() operator
# Tuple slicing
tup = (1, 2, 3, 4, 5)
s1 = slice(3)
s2 = slice(1, 5, 2)
print(tup[s1])
print(tup[s2])
# Negative Tuple slicing
s1 = slice(-3)
s2 = slice(-1, -5, -2)
print(tup[s1])
print(tup[s2])
Output
(1, 2, 3)
(2, 4)
(1, 2)
(5, 3)
The post Python slice() appeared first on ItsMyCode.
Top comments (0)