How to print something only if it exists?

Terry Reedy tjreedy at udel.edu
Thu Sep 6 15:34:13 EDT 2012


On 9/6/2012 1:59 PM, tinnews at isbd.co.uk wrote:
> 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.

What fails is the indexing operation. You can prevent that by slicing 
rather than indexing: fld[1:2], fld[2:3]. These will give '' if there is 
no fld[1], fld[2]. Whether or not this is sensible depends on what you 
want the output to look like in these cases.

-- 
Terry Jan Reedy




More information about the Python-list mailing list