w3resource

Python: slice() function

slice() function

The slice() function is used to get a slice object representing the set of indices specified by range(start, stop, step).

Version:

(Python 3.2.5)

Syntax:

slice(stop)
slice(start, stop[, step])

Parameter:

Name Description Required /
Optional
start

An integer number specify where to start the slicing. Default is 0.

Optional.
stop

An integer number specify where the slice will end.

Required.
step

An integer number specify the step of the slicing. Default is .

Optional.

Return value:

A slice object.

Example: Python slice()

pyStr = 'Python'

# contains indices (0, 1, 2, 3)
# i.e. P, y , t and h
sliceObj = slice(4)

print(pyStr[sliceObj])

# contains indices (1, 5)
# i.e. y and h
sliceObj = slice(1,5, 2)

print(pyStr[sliceObj])

Output:

Pyth
yh

Pictorial Presentation:

Python: Built-in-function - slice() function

Example: Python slice() with negative index

pyStr = 'Python'

# contains indices (-2, -3, -4)
# i.e. o, h and t
sliceObj = slice(-1, -3, -1)

print(pyStr[sliceObj])

Output:

no

Python Code Editor:

Previous: setattr()
Next: sorted()

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.