On 6 September 2012 18:59, <[email protected]> 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.
--
http://mail.python.org/mailman/listinfo/python-list