How to print something only if it exists?
Emile van Sebille
emile at fenx.com
Thu Sep 6 14:19:09 EDT 2012
On 9/6/2012 10:59 AM tinnews at isbd.co.uk said...
> I want to print a series of list elements some of which may not exist,
> e.g. I have a line:-
>
> print day, fld[1], balance, fld[2]
>
> fld[2] doesn't always exist (fld is the result of a split) so the
> print fails when it isn't set.
>
> I know I could simply use an if but ultimately there may be more
> elements of fld in the print and the print may well become more
> complex (most like will be formatted for example). Thus it would be
> good if there was some way to say "print this if it exists".
>
You may be better off ensuring that fld is an appropriate length. One
way may be tweaking the split to return the right numbers of elements:
>>> T = "1,2,3"
>>> flds = (T+","*5).split(",")[:5]
>>> flds
['1', '2', '3', '', '']
Emile
More information about the Python-list
mailing list