Slice Operator in Python

 


Slice Operator

in slice operator, :(colon) is used
It is separated in 3 sections to read data from a sequence
A sequence can be  List, Tuple, Dictionary and String
    [start : end-1 : step]

lets suppose we have a string as sequence below (name is a string)

name = "Techno Xpresss"

 

case 1 : [ :  : ]
  • without passing any value
  • by default 
    • start is 0th index
    • end-1 will be last index
    • step will 1
  • it will print all the data in sequence from start to end


#program

name = "Techno Xpresss"
print (name[ : : ])

#output
Techno Xpresss


case 2 : [start : : ]
  • we can pass only start
  • by default 
    • end-1 will be last index
    • step is 1
  • it will print data till end in sequence from the start position

#program

name = "Techno Xpresss"
print (name[7: : ])

#output
Xpresss



case 3 : [ : end-1 : ]
  • we can pass only end value.
  • by default
    • start is 0th index
    • step is 1
  • it will print data from starting to passed end position-1

#program

name = "Techno Xpresss"
print (name[ :7: ])

#output
Techno



case 4 :[ : : step]

  • we can pass only steps.
  • by default
    • start is 0th index
    • end-1 will be last index
  • It will print data from start to end by passed taking passed step.

#program

name = "Techno Xpresss"
print (name[ : :2])

#output
Tcn pes


case 5 :[start : end-1 : step]

  • we can call all three.
  • every thing will be taken for respective position
  • It will print data starting from passed start position to passed end position -1 and with the passed step

#program

name = "Techno Xpresss"
print (name[0:12: ])
print (name[0:12:3])
print (name[0:12:4])


#output
Techno Xpres
Th r
Tnp


So we can try many combination, but conclusion  is if values were not passed it will take default values.


Lets have look at negative indexing as well


#program

name = "Techno Xpresss"
print (name[-14:-2: ])

#output
Techno Xpres


printing in reverse

#program

name = "Techno Xpresss"
print (name[14: :-1])
print(name[ : :-1])
print(name[-1 : -15: -1])

#output
ssserpX onhceT
ssserpX onhceT
ssserpX onhceT


you can play more by changing values, for a better understanding.





Comments

My photo
Techno Xpresss
Bangalore, Karnataka, India