Spec format to display a blank (empty string) for zero (0)

Is there a format specification option to display null values ​​as empty, otherwise use a format?

>>> from decimal import Decimal
>>> '{:+010,.2f}'.format(Decimal('1234.56'))
'+01,234.56'
>>> '{:???f}'.format(Decimal(0))
''
>>> 

UPDATE:

I need the same behavior as here:

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SectionSeparator

If Python does not have it in standard libraries, please confirm this and I will accept it as an answer.

+3
source share
5 answers

Python , , . .

0

:

print(format(a, '+010,.2f') if a else "")
+5

formatdoes a lot of things, but that’s not what it is for. There is also a very simple solution:

if a == 0:
  print("")
else:
  print(format(a, '+010,.2f'))
0
source
if a:
    print(...)
0
source

How to define a function:

def format_cond(val,fmt,cond=bool,otherwise=''):
    return format(val, fmt) if cond(val) else otherwise
0
source

Source: https://habr.com/ru/post/1780460/


All Articles