Which is a clean way to write this formatting function:
def percent(value,digits=0):
return (\'{0:.%d%%}\' % digits).format(value)
>>> percent(
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%'
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%
* 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.)