Python @ DjangoSpin

Python: Slicing a sequence

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Slicing in Python

Slicing in Python

Slicing means getting a portion of an ordered sequence. An ordered sequence is a sequence whose elements can be accessed using indexes. Examples of ordered sequences are strings, lists, tuples. Here's how you can slice strings in Python.

>>> originalString = "magnanimous"
>>> arrayRepresentationOfOriginalString = '''           # for understanding indexes used later
  
              0   1   2   3   4   5   6   7   8   9  10
              _   _   _   _   _   _   _   _   _   _   _ 
            |   |   |   |   |   |   |   |   |   |   |   |
            | m | a | g | n | a | n | i | m | o | u | s |
            | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ |
            -11 -10  -9  -8  -7  -6  -5  -4  -3  -2  -1
'''
>>> st = originalString   # for easy reference
>>> st[1:5]               # st[x:y] gives us a string starting with st[x] and ending with st[y-1]
'agna'
>>> st[-5:-1]         # -5 is actually 6 and -1 is actually 10, so this becomes st[6:10]
'imou'
>>> st[1:5:1]         # st[x:y:z] gives us a string starting with st[x], with a step over size of 1, ending with st[y-1]
'agna'
>>> st[1:5:2]         # starting at index 1, ending with index 5-1, with a difference of 2 between the indexes of characters
'an'
>>> st[5:1:-1]        # FOR NEGATIVE STEP SIZE: begin at index 5, move in the opposite direction i.e. left, finish at index 1 + 1.
'nang'
>>> st[-5:-8:-1]
'ina'
>>> st[:5]            # select everything from index 0 to 5-1
'magna'
>>> st[5:]            # select everything from index 5 till the end of the originalString
'nimous'
>>> st[:]             # gives the originalString itself
'magnanimous'
 
# Slicing takes characters from left to right of a string, unless you specify a negative step size. What this means is that by default, the first number should should be the index of a character on the left of character whose index is denoted by the second number, UNLESS a negative step size is specified, in which case, the first number should be the index of a character on the right of the character whose index is denoted by the second number. Not confusing, right?

Expand for slicing scenarios in lists, tuples, sets & dictionaries.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply