FLexible formatted text involving nested lists?

Tino Wildenhain tino at wildenhain.de
Fri Oct 10 10:31:41 EDT 2008


Hi,

RossRGK wrote:
> Kerri Reno wrote:
>> Ross,
>>
>> I'm no expert in python, so excuse me if this is inane.
>>
>> What I would do is have fmts be a dictionary where
>> fmts = { 3 = 'oats %0d kilos over %0d days with %0d workers',
>>          2 = 'barley %0d lbs for %0d hours',
>>          1 = 'apples %0d baskets'}
>>
>> then something like
>>   for x in bigList:
>>      print fmts[len(x)] % x
>>
>> I didn't test this, but in theory it should work.
>>
>> Hope this helps,
>> Kerri
> 
> 
> Thx for the suggestion - i think that would match the number of fields 
> to the number of parameters in the specific example but not the general 
> case.  ie fmts[3] could have 3fields this time, but might be 2 another 
> time or something else.

Maybe you want to reconsider your approach and instead of use "lists"
just a dict or class with the correct naming?

If you use a class you could also attach all the meta information
for formatting.

Dicts are easily aliased to your formats using named arguments:

'oats %(weight)0d kilos over %(days)0d days with %(workers)0d workers' % 
dict(weight=5,days=3,workers=10)

which would make more sense when you read it and/or edit the sentence
sometime later. You could also consider extending the attributes
to have the unit (e.g. kg, pound, days, ...) attached to it
and decide to add a clever get() method to your container class
(which replaces the list) and use it like this:

'oats %(weight.kg)s ...' % yourinstance ...

where instance.get() would be called with 'weight.kg',
splits on the . for the attribute: weight,

calls self.weight.format(unit='kg')

to retrieve "5 kilos" or something :-)

Just some random thoughts.

Regards
Tino
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20081010/4fa96707/attachment-0001.bin>


More information about the Python-list mailing list