Python slice()
The slice() is a built-in python function that slice the given object.(List, String, etc)
Python slice()
The syntax of slice() is:
1
2
slice(start, stop, step)
slice() Parameters
The slice() functions takes three parameters as argument:
- start (optional) - An integer number specifying at which position to start the slicing. Default is 0
- stop - An integer number specifying at which position to end the slicing
- step (optional) - Optional. An integer number specifying the step of the slicing. Default is 1.
Lets see an example of python slice() function.
Example 1: How to use slice() in python?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Python program to demonstrate
# slice() operator
# String slicing
String ='PythonScholar'
s1 = slice(3)
s2 = slice(1, 5, 2)
print("String slicing")
print(String[s1])
print(String[s2])
# List slicing
L = [1, 2, 3, 4, 5]
s1 = slice(3)
s2 = slice(1, 5, 2)
print("\nList slicing")
print(L[s1])
print(L[s2])
# Tuple slicing
T = (1, 2, 3, 4, 5)
s1 = slice(3)
s2 = slice(1, 5, 2)
print("\nTuple slicing")
print(T[s1])
print(T[s2])
Output:
1
2
3
4
5
6
7
8
9
10
11
12
String slicing
Pyt
yh
List slicing
[1, 2, 3]
[2, 4]
Tuple slicing
(1, 2, 3)
(2, 4)
This post is licensed under CC BY 4.0 by the author.