I need a neat way to print nothing or a number

Chris Angelico rosuav at gmail.com
Tue Mar 26 14:48:39 EDT 2013


On Wed, Mar 27, 2013 at 4:21 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 03/26/2013 10:06 AM, Wolfgang Maier wrote:
>>
>> Chris Angelico <rosuav <at> gmail.com> writes:
>>
>>>
>>> Try printing out this expression:
>>>
>>> "%.2f"%value if value else ''
>>>
>>> Without the rest of your code I can't tell you how to plug that in,
>>> but a ternary expression is a good fit here.
>>>
>>> ChrisA
>>>
>>
>> Unfortunately, that's not working, but gives a TypeError: a float is
>> required
>> when the first value evaluates to False.
>> Apparently it's not that easy to combine number formatting with logical
>> operators - the same happens with my idea ('{:.2f}').format(value or '').
>
>
> Use parens then:
>
> ("%.2f" % value) if value else ''

According to the operator precedence table, the parens are unnecessary there.

ChrisA



More information about the Python-list mailing list