29
loading...
This website collects cookies to deliver better user experience
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()
is:**slice(start, stop, step)**
slice()
method can take three parameters.None
.None
.None
.slice()
method returns a sliced object containing elements in the given range. __getitem__ ()
and __len()__
method.# Python program to demonstrate slice() operator
# String slicing
str = 'ItsMyPythonCode'
s1 = slice(3)
s2 = slice(5, 11,1)
print(str[s1])
print(str[s2])
Its
Python
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])
ItsMyPython
nohtyP
# 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])
[1, 2, 3]
[2, 4]
[1, 2]
[5, 3]
# 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])
(1, 2, 3)
(2, 4)
(1, 2)
(5, 3)