Slicing
The meaning of word “slice” is “a part of”. In the same way , in python the term “string slice” refers to a part of the string, where strings are sliced using a range of indices.
Suppose we have a string named “str”. , if we give str[n:m] where n and m are integers and valid indices. Python will return a part of string by returning the characters falling between indices n and m. starting from
n,n+1,n+2,n+3….m-1.
Example:1
n=”computer”
Positive index
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
c |
O |
m |
p |
u |
t |
e |
r |
-8 |
-7 |
-6 |
-5 |
-4 |
-3 |
-2 |
-1 |
Negative index
n=”computer”
print(n)
print(n[0:4])
print(n[1:3])
print(n[4:7])
print(n[2:6])
print(n[3:7])
output:
computer
comp
om
ute
mput
pute
slicing with negative index
Example:
n=”computer”
Positive index
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
c |
o |
m |
p |
u |
t |
e |
r |
-8 |
-7 |
-6 |
-5 |
-4 |
-3 |
-2 |
-1 |
Negative index
n=”computer”
print(n)
print(n[0:4])
print(n[-3:])
print(n[-7:-2])
print(n[-6:])
print(n[-6:4])
output:
computer
comp
ter
omput
mputer
mp