newbie string question

Fernando Pérez fperez528 at yahoo.com
Thu Jun 20 23:52:01 EDT 2002


Don Low wrote:

> So if I understand, pystr[3] refers to the subscript index, but pystr[3:]
> refers to the slice index. pystr[2:5] means slice at slice index 2 and 5,
> not start at subscript index 2 and slice at slice index 5.
> 
> I just want to understand this once and for all.

The easiest way to understand this is to build a list which is a range. There 
you have a one-to-one mapping between list indices and elements. Then slice 
it to your heart's content and the behavior of : and friends will become 
second nature:

In [1]: x=range(10)

In [2]: x
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [3]: x[5]
Out[3]: 5

In [4]: x[3:7]
Out[4]: [3, 4, 5, 6]

In [5]: x[:]
Out[5]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [6]: x[5:]
Out[6]: [5, 6, 7, 8, 9]

In [7]: x[-1]
Out[7]: 9

In [8]: x[-5]
Out[8]: 5

In [9]: x[-5:]
Out[9]: [5, 6, 7, 8, 9]


cheers,

f



More information about the Python-list mailing list