Which is a clean way to write this formatting function:
def percent(value,digits=0):
return ('{0:.%d%%}' % digits).format(value)
>>> percent(0.1565)
'16%'
>>> percent(0.1565,2)
'15.65%'
the problem is formatting a number with a given number of digits, I don't like to use both '%' operator and format method.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
Variable names should be brief yet descriptive. Variable names can contain capital letters (A ~ Z) or lowercase letters (a ~ z), and underscores ( _ ). Variable names cannot begin with a number.
Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.
%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.
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%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With