Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #29060

RE: How to print something only if it exists?

From "Prasad, Ramit" <ramit.prasad@jpmorgan.com>
Subject RE: How to print something only if it exists?
Date 2012-09-13 17:48 +0000
References <9s4nh9-8dr.ln1@chris.zbmc.eu>
Newsgroups comp.lang.python
Message-ID <mailman.625.1347559650.27098.python-list@python.org> (permalink)

Show all headers | View raw


tinnews@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.
> 
> 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 can use an inline if-else statement.

print day, fld[1], balance, fld[2] if len(fld) >= 3 else ''


Ramit
--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

How to print something only if it exists? tinnews@isbd.co.uk - 2012-09-06 18:59 +0100
  Re: How to print something only if it exists? Emile van Sebille <emile@fenx.com> - 2012-09-06 11:19 -0700
  Re: How to print something only if it exists? Dave Angel <d@davea.name> - 2012-09-06 14:18 -0400
    Re: How to print something only if it exists? tinnews@isbd.co.uk - 2012-09-08 11:02 +0100
      Re: How to print something only if it exists? Dave Angel <d@davea.name> - 2012-09-08 07:08 -0400
  Re: How to print something only if it exists? Terry Reedy <tjreedy@udel.edu> - 2012-09-06 15:34 -0400
  Re: How to print something only if it exists? Hans Mulder <hansmu@xs4all.nl> - 2012-09-07 11:37 +0200
  Re: How to print something only if it exists? Roy Smith <roy@panix.com> - 2012-09-07 09:16 -0400
  RE: How to print something only if it exists? "Prasad, Ramit" <ramit.prasad@jpmorgan.com> - 2012-09-13 17:48 +0000

csiph-web