[Python-Dev] An ability to specify start and length of slices
Duncan Booth
duncan.booth at suttoncourtenay.org.uk
Sat Jun 5 08:18:18 EDT 2004
Noam Raphael <noamr at myrealbox.com> wrote in
news:40BFA134.10404 at myrealbox.com:
> Many times I find myself asking for a slice of a specific length, rather
> than a slice with a specific end. I suggest to add the syntax
> object[start:>length] (or object[start:>length:jump]), beside the
> existing syntax.
Can I suggest that rather than adding obscure punctuation, we could just
have a keyword parameter 'length' to the slice type. So your examples above
become:
object[slice(start, length=length)]
and
object[slice(start, length=length, step=jump)]
I think it is much more in the spirit of Python to write such things out
explicitly.
>
>
> Two examples:
>
> 1. Say I have a list with the number of panda bears hunted in each
> month, starting from 1900. Now I want to know how many panda bears were
> hunted in year y. Currently, I have to write something like this:
> sum(huntedPandas[(y-1900)*12:(y-1900)*12+12])
> If my suggestion is accepted, I would be able to write:
> sum(huntedPandas[(y-1900)*12:>12])
sum(huntedPandas[slice(y-1900)*12, length=12)]
>
> 2. Many data files contain fields of fixed length. Just an example: say
> I want to get the color of the first pixel of a 24-bit color BMP file.
> Say I have a function which gets a 4-byte string and converts it into a
> 32-bit integer. The four bytes, from byte no. 10, are the size of the
> header, in bytes. Right now, if I don't want to use temporary variables,
> I have to write:
> picture[s2i(picture[10:14]):s2i(picture[10:14])+4]
> I think this is nicer (and quicker):
> picture[s2i(picture[10:>4]):>4]
>
picture[slice(s2i(picture[slice(10, length=4)]), length=4)
although you still need to split that up with some temporary variables to
make the code self explanatory.
BTW, in Python 2.3.x slice silently ignores any keyword parameters it is
given, so the above code will actually run right now, it just won't give
the expected result!
More information about the Python-Dev
mailing list