I need a neat way to print nothing or a number

Peter Otten __peter__ at web.de
Tue Mar 26 13:22:21 EDT 2013


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

Here's a round-about way:

class Prepare:
    def __init__(self, value):
        self.value = value
    def __format__(self, spec):
        if self.value is None or self.value == 0:
            return format(0.0, spec).replace(".", " ").replace("0", " ")
        elif isinstance(self.value, str):
            return self.value.rjust(len(format(0.0, spec)))
        return format(self.value, spec)

def prepare(row):
    return map(Prepare, row)

data = [
    ("Credit", "Debit", "Description"),
    (100, 0, "Initial balance"),
    (123.45, None, "Payment for cabbages"),
    (0.0, 202.0, "Telephone bill"),
]

for row in data:
    print("{:10.2f} {:10.2f} {}".format(*prepare(row)))






More information about the Python-list mailing list