Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable number of digit in format string

Tags:

python

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.

like image 537
Emanuele Paolini Avatar asked Feb 18 '13 08:02

Emanuele Paolini


People also ask

What string method is used to format values in a string?

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.

How do you format a variable name?

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.

Can you use .format on variables Python?

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.

What does %d do in Java?

%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.


2 Answers

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%'
like image 191
eumiro Avatar answered Sep 21 '22 12:09

eumiro


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%
like image 32
Inbar Rose Avatar answered Sep 22 '22 12:09

Inbar Rose