variable number of digit in format string

后端 未结 3 454
时光说笑
时光说笑 2020-12-16 00:14

Which is a clean way to write this formatting function:

def percent(value,digits=0):
    return (\'{0:.%d%%}\' % digits).format(value)

>>> percent(         


        
3条回答
  •  难免孤独
    2020-12-16 01:16

    From the docs:

    Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

    Example:

    def percent(value, digits=0):
        print '%.*f%%' % (digits, value*100)
    >>> percent(0.1565, 2)
    15.65%
    

提交回复
热议问题