enhancing slicing

Chad Franklin Netzer cnetzer at Stanford.EDU
Thu Aug 23 19:52:26 EDT 2001


"Steve Holden" <sholden at holdenweb.com> writes:

>If I can remember my Icon correctly its slicing mechanism recognised signs
>as significant, so

>    seq[a:+b]

>meant take a slice of length b starting at position a, whereas

>    seq[a:b]


It seems some people missed the point of the post from Grant
(gbreed at cix.compulink.co.uk).  Perhaps the british humor was too droll.
In any case, I apologize if this post appears pretentious, but I'll
explain the joke (those newer to python probably missed it).

Grant suggested we "adopt" a notation of v[5 :][: 2], rather than Juan's
(the original poster) v[5 # 2].  He then suggested that he write up a
proposal for this "new operator". :)

As Will Ware pointed out, this already does (almost) EXACTLY what the
original poster wanted.  The v[5:] returns a new sequence that begins at
the fifth element of the original (Hmmm, The Fifth Element... silly
movie.), and the [:2] then truncates it after the second element.

So rather than v[a # b] use v[a:][:b].
And rather than v[a # -b] use v[:a][-b:]

Therefore, there are already ways to accomplish what the original poster
wanted, but they involve slightly more intricate and verbose notation (as
well as an understanding of all the forms of slicing.)  In both cases,
they allow for expressions a or b to be evaluated once, inline.

I actually use this idiom semi-frequently in text processing, although
rarely (if ever) do I clump the two slices back to back like this.

So, Juan, does that help answer your original question?  It can be done,
just as you want, with a few extra characters (and careful ordering of the
slice)

Humbly yours,

-- 
Chad Netzer
chad.netzer at stanfordalumni.org
-- 
Chad Netzer
chad.netzer at stanfordalumni.org




More information about the Python-list mailing list