Python: Slicing

As I mentioned here: A sequence is a special data structure in Python where data elements can be referenced thru numbers, an index so to speak.

This hasn’t been the entire truth. Actually data elements in a sequence can be also referenced thru ranges, a pair of start and end index so to speak, separated by a colon. This would return another string when used on a string or another list when used on lists. Neither the start nor the end index has to be specified: 0 would be the default for the start index, and when no ending index is specified then the sequence will be returned up to the very end.

Negative indexing can be used to index a sequence from the right ( or from the end ). Thus –1 addresses the last element in a sequence.

Those ranges always specify the first element to retrieve and the last element not to retrieve, thus [0:2] would tell Python to get the first and second element of the sequence and stop at the third element ( the one with index 2; remember: indexing starts with 0 ). [0:-1] would tell Python to get all the elements from a sequence except the last one.

Here are a few examples done with a string:

>>> str = "We will we will rock you !"
>>> str[0]
>>> str[-1]
>>> str[0:2]
>>> str[-5:]
'you !'
>>> str[-5:-1]
'you '
>>> str[3:-5]
'will we will rock '
>>> str[:-2]
'We will we will rock you'

>>> str[:]
'We will we will rock you !'


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: