The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol (implements __getitem__() and __len__() method).
Slice object represents the indices specified by range(start, stop, step).
The syntax of slice() are:
slice(stop) slice(start, stop, step)
slice() mainly takes three parameters which have the same meaning in both constructs:
If a single parameter is passed, start and step are set to None.
slice() returns a slice object used to slice a sequence in the given indices.
# contains indices (0, 1, 2) print(slice(3)) # contains indices (1, 3) print(slice(1, 5, 2))
When you run the program, the output will be:
slice(None, 3, None) slice(1, 5, 2)
pyString = 'Python' # contains indices (0, 1, 2) # i.e. P, y and t sObject = slice(3) print(pyString[sObject]) # contains indices (1, 3) # i.e. y and h sObject = slice(1, 5, 2) print(pyString[sObject])
Pyt yh
pyString = 'Python' # contains indices (-1, -2, -3) # i.e. n, o and h sObject = slice(-1, -4, -1) print(pyString[sObject])
noh
pyList = ['P', 'y', 't', 'h', 'o', 'n'] pyTuple = ('P', 'y', 't', 'h', 'o', 'n') # contains indices (0, 1, 2) # i.e. P, y and t sObject = slice(3) # slice a list print(pyList[sObject]) # contains indices (1, 3) # i.e. y and h sObject = slice(1, 5, 2) # slice a tuple print(pyTuple[sObject])
['P', 'y', 't'] ('y', 'h')
pyList = ['P', 'y', 't', 'h', 'o', 'n'] pyTuple = ('P', 'y', 't', 'h', 'o', 'n') # contains indices (-1, -2, -3) # i.e. n, o and h sObject = slice(-1, -4, -1) # slice a list print(pyList[sObject]) # contains indices (-1, -3) # i.e. n and h sObject = slice(-1, -5, -2) # slice a tuple print(pyTuple[sObject])
['n', 'o', 'h'] ('n', 'h')
The slice object can be substituted with the indexing syntax in Python.
You can alternately use the following syntax for slicing:
obj[start:stop:step]
pyString = 'Python' # contains indices (0, 1, 2) # i.e. P, y and t print(pyString[0:3]) # contains indices (1, 3) # i.e. y and h print(pyString[1:5:2])