How to print something only if it exists?
Joshua Landau
joshua.landau.ws at gmail.com
Thu Sep 6 15:51:22 EDT 2012
On 6 September 2012 18:59, <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 I might do is simply make a class that wraps the list.
class SafeIndex:
def __init__(self, lst, safety=""):
self.list = lst
self.safety = ""
def __getitem__(self, n):
try:
return self.list[n]
except IndexError:
return self.safety
si = SafeIndex(range(20))
Then just index the SafeIndex with the print and abandon it after.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120906/ca7e24a6/attachment.html>
More information about the Python-list
mailing list