FRIHOST • FORUMS • SEARCH • FAQ • TOS • BLOGS • COMPETITIONS
You are invited to Log in or Register a free Frihost Account!

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:
Code:

>>> str = "We will we will rock you !"
>>> str[0]
'W'
>>> str[-1]
'!'
>>> str[0:2]
'We'
>>> 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 !'




0 blog comments below




FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.