I need a neat way to print nothing or a number

Ethan Furman ethan at stoneleaf.us
Tue Mar 26 13:21:35 EDT 2013


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 ''

--
~Ethan~



More information about the Python-list mailing list