开发者

Format spec to display blank (empty string) for zero (0)

Is there an option in format specification to display zero values as blank, otherwise use 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 doesn't have it in standard libraries, please confirm this an开发者_如何学Cd i will accept it as the answer.


No, you can't currently do it via a Python format specification. Use a conditional expression instead. For example:

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


How about define a function:

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


Python does not have a section separator functionality so you can have different formats for positive, negative or zero numbers in the same string. You'll have to use separate format strings.


I was counting the frequency of occurrence of upper and lower case vowels in a piece of text.

# display each vowel and its frequency of both upper and lower case occurrence
for key, value in lower.items():
    print("{:^6}\t{:5}\t{:5}".format(key, value if value > 0 else "", upper[key.upper()] if upper[key.upper()] else ""))

Vowel   Lower   Upper
------  -----   -----
  a        52       9
  e        80        
  i        37        
  o        50       3
  u        21        
        =====   =====
          240      12 


format does lots of things, but this isn't what it is designed for. There is also a very simple solution:

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


if a:
    print(...)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜