Re: [Tutor] dicey slices

Magnus Lycka magnus at thinkware.se
Mon Apr 19 12:08:36 EDT 2004


>  +---+---+---+---+---+ 
>  | H | e | l | p | A |
>  +---+---+---+---+---+ 
>  0   1   2   3   4   5 
> - - -5  -4  -3  -2  -1

This picture isn't quite right. The negative indices are wrong.
It should be:

>  +---+---+---+---+---+ 
>  | H | e | l | p | A |
>  +---+---+---+---+---+ 
>  0   1   2   3   4   5 
> -5  -4  -3  -2  -1

E.g.

>>> s = "HelpA"
>>> s[4:5]
'A'
>>> s[-2:-1]
'p'
>>> s[-1:]
'A'

There is no negative zero in Python, so there is no 
way to explicitly name the upper bound if you are
using negative indices. For instance, you can do this:

>>> for i in range(0,len(s),2):
	lower, upper = i, i+2
	print lower, upper, s[lower:upper]

	
0 2 He
2 4 lp
4 6 A

But trying to do the same trick with negative bounds won't work

>>> for i in range(0,len(s),2):
	lower, upper = -i-2, -i
	print lower, upper, s[lower:upper]

	
-2 0 
-4 -2 el
-6 -4 H

See? The first line "ought" to have printed "-2 -0 pA", but
there is no -0, and 0 is before the first position, not after
the last.

Actually, it just occurred to me that you can use s[-2:None]
instead of s[-2:]. (Is this a documented feature or does it
just happen to work?)

This means that you can do:

>>> for i in range(0,len(s),2):
	lower, upper = i or None, i+2 or None
	print lower, upper, s[lower:upper]

	
None 2 He
2 4 lp
4 6 A
>>> for i in range(0,len(s),2):
	lower, upper = -i-2 or None, -i or None
	print lower, upper, s[lower:upper]

	
-2 None pA
-4 -2 el
-6 -4 H

Yes! Our symmetry is back!


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list