89DEVs

Python slice() function

overview of slice()

The slice() function returns a slice object. The slice object is used to slice any object like a string, tuple, list, or range. It can be used on any object, that implements the __getitem__() and __len()__ method.

use of slice()

The slice() function can be used to slice objects. For example, it is possible to slice a string based on the specified arguments. # use of slice() myString = 'Python' sliceObject = slice(3) print(sliceObject) print(myString[sliceObject]) The variable myString contains the string 'Python'. Then, a slice object is created to slice the first three letters of the string. First, the slice object is returned and then the slice object is applied to slice the string accordingly. slice(None, 3, None) Pyt

syntax of slice()

The syntax of the slice() function is: slice([start, stop, step])

arguments of slice()

The slice() function requires at least one and up to three arguments.
argument required description
start optional the starting integer value where the slice begins, default value is None
stop required the ending integer value where the slice ends, the slicing stops at index -1
step optional the step defines the increment between each index sliced, default value is None

return value of slice()

The slice() function returns a slice object, which is used to slice objects like strings, tuples, lists or ranges.

                
        

Summary


Click to jump to section