variable number of digit in format string

后端 未结 3 446
时光说笑
时光说笑 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 00:58

    I like this one:

    '{0:.{1}%}'.format(value, digits)
    

    Test:

    >> '{0:.{1}%}'.format(0.1565, 0)
    '16%'
    >> '{0:.{1}%}'.format(0.1565, 2)
    '15.65%'
    
    0 讨论(0)
  • 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%
    
    0 讨论(0)
  • 2020-12-16 01:17

    * does what you want, for printf-style string formatting.

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

    Advanced string formatting (defined in PEP 3101 and documented in 7.1.3. Format String Syntax) doesn't seem to be capable of doing this in one pass. (See 7.1.3.1. Format Specification Mini-Language: precision is integer only.)

    0 讨论(0)
提交回复
热议问题