30 Apr 2014

A look at python slicing

In this post i'm going to take a look at basic of python slicing which can be quite useful.
Let say we have ptr = "POINTER" a string field, i'll use that string to show the different types of slicing.

Get first n elemenst using [:n]
ptr[:1]    --> "P"
ptr[:2]   --> "PO"
ptr[:3]   --> "POI"

Remove first n elements using [n:]
ptr[1:]  --> "OINTER"
ptr[2:]  --> "INTER"
ptr[3:]  --> "NTER"

Get last n elements using [-n:]
ptr[-1:]  --> "R"      
ptr[-2:]  --> "ER"    
ptr[-3:]  --> "TER"   

Remove last n elements using [:-n]
ptr[:-1]  --> "POINTE"
ptr[:-2]  --> "POINT" 
ptr[:-3]  --> "POIN"

  
Get sub elemens using [n:m]
It given sub elements from n (inclusive) m(exclusive).
ptr[0:3] --> "POI"

Get sub elemens using [n:-m]
a). first apply [:-m] .i.e. removes last m elements,
b). then show all elements from n (inclusive).
ptr[0:-1]  --> "POINTE"
ptr[2:-3]  --> "IN

 Get sub elemens using [-n:m]
a). first apply [:m] .i.e. get first m elements,
b). get n last elements.
c) get common elements from a) and b)

example :  ptr[-1:7]  -->  'R'
a) ptr[:7] ----> X = 'POINTER' 
b) ptr[-1]  --->  Y = 'R'
c) apply  intersection(X, Y) --> 'R' 
example :  ptr[-1:6]   --> ""
a) ptr[:6]  ----> X = 'POINTE'
b) ptr[-1]  --->  Y = 'R'
c) apply  intersection(X, Y) --> nothing.

One intesting observation in here is :
[-7:1] => 'P'
[-6:2] => 'O'
[-5:3] => 'I'
........
........
 [-1:7] => 'R'

Following code implement above behaviour
ptr_len=len(ptr)+1
for i in range(1, ptr_len):
  p
tr_len=ptr_len-1
  print ptr[-p
tr_len:i]


Thats it. I hope,  i have demonstrated in very simple to get you understand python slicing.



No comments:

Post a Comment