Specify start and length, beside start and end, in slices

Noam Raphael noamr at correctme.users.sourcephorge.net
Sat May 22 17:01:12 EDT 2004


Hello,

Larry Bates wrote:
> I think it is odd that I have never encounter
> many of these types of constructs repeatedly in
> my code.  Perhaps you could share a little more
> of where you see this type of think popping up
> a lot?  I suspect that there is another method
> for solving the problem that might be faster
> and easier to read/program.
> 
> Larry Bates,
> Syscon, Inc.
> 
> 

With pleasure. Here are 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])

(Yes, I know that it may also be expressed as
sum(huntedPandas[(y-1900)*12:(y-1901)*12]), but it's less clear what I 
mean, and it's still longer)

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]

Thanks for your interest,
Noam Raphael



More information about the Python-list mailing list