FLexible formatted text involving nested lists?
nobody at nospam.noway
Thu Oct 9 22:36:35 CEST 2008
I'm having trouble getting my head around a solution for a situation
where I need to flexibly format some text with a varying number of
Here's a simplified description of my challenge...
I have a list of lists called bigList:
bigList = [ little, small, tiny]
The sub-lists have varying sizes. I won't know how many items they have
but it will be between 0 and 3
So perhaps little = [3, 2, 7]
small = [6,4]
tiny = 
The values in those sub lists correspond to formatted print strings. The
formatting strings will change over time and they are in a list called
fmts = [fmtA, fmtB, fmtC] where
fmtA = 'oats %0d kilos over %0d days with %0d workers'
fmtB = 'barley %0d lbs for %0d hours'
fmtC = 'apples %0d baskets'
If I knew how many fields were in each 'sub-list' in bigList ahead of
time, and it never changed I could awkwardly do this:
print fmtA %(little, little, little)
print fmtB %(small, small)
print fmtC %(tiny)
print fmts %(bigList, bigList, bigList)
print fmts %(bigList, bigList)
print fmts %(bigList)
Both approaches would yield:
oats 3 kilos over 2 days with 7 workers
barley 6 lbs for 4 hours
apples 2 baskets
Now my challenge: since the number of fields is unknown at design time,
my app needs to add be able to flexibly handle this.
I though maybe I could use a loop that figures things out as it goes
for fmtString in fmts
numbOfFields = len(fmt[i])
print fmtString %(bigList[i][ need "for 0 to numbOffields" worth of
But I don't know how to have a number of items in the print expression
that align to the numbOfFields value!? Is there some other approach I
I thought perhaps it would accomodate extra elements in the %(...) part
of the formatted print expression which would be ignored, but that
Maybe I have to break my fmts up and do a field at a time? Any thoughts
are appreciated :)
More information about the Python-list