import and package confusion

Terry Reedy tjreedy at udel.edu
Thu Apr 30 22:20:29 CEST 2009


Dale Amon wrote:

> Now I can move on to parsing those pesky Fortran card
> images... There wouldn't happen to be a way to take n
> continguous slices from a string (card image) where each 
> slice may be a different length would there? Fortran you 
> know. No spaces between input fields. :-)
> 
> I know a way to do it, iterating over a list of slice sizes,

Yes.

> perhaps in a list comprehension, but some of the august python 
> personages here no doubt know better ways.

No.  Off the top of my head, here is what I would do something like 
(untested)

def card_slice(card, sizes):
   "Card is data input string. Sizes is an iterable of int field sizes, 
where negatives are skipped fields.  Return list of strings."
   pos, ret = 0, []
   for i in sizes:
     if i > 0:
       ret.append(card[pos:pos+i])
     else:
       i = -i
     pos += i
   return ret

To elaborate this, make sizes an iterable of (size, class) pairs, where 
class is str, int, or float (for Fortran) or other for more generel use. 
  Then
   ...
   for i,c in sizes:
     if i > 0:
       ret.append(c(card[pos:pos+i]))

Terry Jan Reedy




More information about the Python-list mailing list