May-04-2017, 09:52 AM
May-04-2017, 10:27 AM
that is called slicing. you can slice any iterable - string, list, tuple, etc. the general syntax is
someiterable[start:stop:step]note that index is 0-based
May-04-2017, 10:45 AM
I am answering this, partly to also understand the question for my own use.
The "anomoly" that I see, coming from a non Python background, is:
The [start] 3 is counting from a position of 0 rather than 1
But the [stop] 7 is counting from 1 rather than 0
The third element is as said by @buran is a [step] - so in this situation may not make any difference, as 1 may be the normal step. If you changed this to -1 you would be reversing the string as you are stepping backwards.
Do others agree with the starting/counting positions [start from 0] and [stop from 1] or have I misunderstood?
Bass
The "anomoly" that I see, coming from a non Python background, is:
The [start] 3 is counting from a position of 0 rather than 1
But the [stop] 7 is counting from 1 rather than 0
The third element is as said by @buran is a [step] - so in this situation may not make any difference, as 1 may be the normal step. If you changed this to -1 you would be reversing the string as you are stepping backwards.
Do others agree with the starting/counting positions [start from 0] and [stop from 1] or have I misunderstood?
Bass
May-04-2017, 10:52 AM
(May-04-2017, 10:45 AM)Bass Wrote: [ -> ]The [start] 3 is counting from a position of 0 rather than 1
But the [stop] 7 is counting from 1 rather than 0
In the programming indexes are almost all of the time 0-based.
stop is counting from 0 too, however it's starting from (including) start index up to (but not including) stop index.
May-04-2017, 10:56 AM
Also note that you can have negative indexes
>>> 'somestring'[-5:-1] 'trin'in this case indexes go from right to left.
May-04-2017, 10:56 AM
Got you. Understand now.
Thanks
Bass
Thanks
Bass
May-04-2017, 11:16 AM
Yo can also use
None
as either start
or stop
indices - as start
it means from 0, as end
- till end. In [95]: l = list(range(3)) In [96]: l[None:] Out[96]: [0, 1, 2] In [97]: l[:None] Out[97]: [0, 1, 2]The latter is especially useful when using variable as
stop
index - l[0:]
is ugly, but legal; however, there's no other way for stop index to mark the end of the listMay-04-2017, 11:20 AM
Actually, I think I have never seen None used as index. i.e. I would say that actually it's legal , but ugly :-)
May-04-2017, 11:27 AM
(May-04-2017, 11:20 AM)buran Wrote: [ -> ]Actually, I think I have never seen None used as index. i.e. I would say that actually it's legal , but ugly :-)Actually, for a slice till the end you may use any index that is larger than or equal to list/string lenth - but that in case that you know length in advance.
And it's not intended for direct use in code, actually that would be plain stupid - that was just a demonstration.
It is useful technique when
stop
index is passed as a variable...