How to print something only if it exists?

Dave Angel d at davea.name
Sat Sep 8 07:08:09 EDT 2012


On 09/08/2012 06:02 AM, tinnews at isbd.co.uk wrote:
> Dave Angel <d at davea.name> wrote:
>> Would you like to define "exists" ?  A list is not sparse, so all items
>> exist if their subscript is less than the length of the list.  So all
>> you need to do is compare 2 to len(fld).
>>
> Yes, a I said a simple len(fld) will tell me if fld[2] 'exists' but it
> gets messy if I have to do it in the middle of the print sequence.
>
>
>> But perhaps there's another approach.  Just what DO you want to print if
>> fld(1) exists, but fld(2) does not?  Do you still want to print out day,
>> fld(1), and balance?  Or do you want to skip balance as well?
>>
> Here's a sample of the file whose lines are being split() :-
>
>     01     JB      0.00    Start of 2012, Initial balance
>     02     BB      0.00
>     13     ZB      0.00
>
> I want to print out everything, it's just that in some cases there's
> no descriptive text (the bit that ends up in fld[2]).
>
>
>> if you literally want nothing printed for list elements beyond the end,
>> then I'd add some extra empty-strings to the end of the list.
>>
>> fld.extend("" * 5)
>>
>> Now, subscripts 0 through 4 inclusive will work, as specified.
>>
> That's probably the simplest approach, thank you.
>

If there literally is only one missing field, and at the end, then you
could use fld.append("") instead.  Or better, you could do something like
   if len(fld) == 2 : fld.append(""")

This may be longer, but at least it's in one place -- the place where
the split is occurring.  And it pretty much states that the fld2 is
optional.

You ought to consider what error to report if you encounter a line with
missing fields that ARE required.



-- 

DaveA




More information about the Python-list mailing list