16

I am a python newbie.I am just getting acquainted with format method.

From a book that I am reading to learn python

What Python does in the format method is that it substitutes each argument
value into the place of the specification. There can be more detailed specifications
such as:
decimal (.) precision of 3 for float '0.333'
>>> '{0:.3}'.format(1/3)
fill with underscores (_) with the text centered
(^) to 11 width '___hello___'
>>> '{0:_^11}'.format('hello')
keyword-based 'Swaroop wrote A Byte of Python'
>>> '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python')

In the python interpreter if I try

print('{0:.3}'.format(1/3))

It gives the error

 File "", line 24, in 
ValueError: Precision not allowed in integer format specifier 
0

4 Answers 4

14

To print the floating point numbers, you have to have atleast one of the inputs as floats, like this

print('{0:.3}'.format(1.0/3))

If both the inputs are integers to the division operator, the returned result will also be in int, with the decimal part truncated.

Output

0.333

You can convert the data to float with float function, like this

data = 1
print('{0:.3}'.format(float(data) / 3))
Sign up to request clarification or add additional context in comments.

2 Comments

what does '{0:.3} mean? how does format substitute for these values?
@liv2hak, 0 is the first argument in the format function.. The colon is just a separator between the data element getting passed in and the formatting. .3 is telling it to format it with 3 characters to the right of the decimal.
14

It's better to add f:

In [9]: print('{0:.3f}'.format(1/3))
0.000

in this way you could notice that 1/3 gives an integer and then correct that to 1./3 or 1/3. .

Comments

5

It is worth noting that this error will only happen in python 2. In python 3, division always returns a float.

You can replicate this with the from __future__ import division statement in python 2.

~$ python
Python 2.7.6 
>>> '{0:.3}'.format(1/3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Precision not allowed in integer format specifier
>>> from __future__ import division
>>> '{0:.3}'.format(1/3)
'0.333'

Comments

1

Python3 fstring Examples:

Decimals

# Set the Result to a variable:
a = 1/3
# Format the result :.3f is the length of the digits "AFTER" the decial point.
print(f"{a:.3f}")
# Returns: 0.333

print(f"{a:.6f}")
# Returns: 0.333333

print(f"{a:.32f}")
# Returns: 0.33333333333333331482961625624739

print(f"{a:.50f}")
# Returns: 0.33333333333333331482961625624739099293947219848633

print(f"{a:.55f}")
# Returns: 0.3333333333333333148296162562473909929394721984863281250

# # NOTE: this does round see the difference between the ending of .50 & .55

Digits & Decimals

# You can do the same for leading zeros:
a = (1/3) + 145630

print(f"{a:016.03f}")

# Returns 000000145630.333

# if you don't want to lead with Zeros and just spaces.
print(f"{a:16.03f}")
# Returns "      145630.333"
# # NOTE: 
# With this one - notice there are only 12 Digits/Spaces Left of the decimal.

print(f"{a:016.55f}")
# Returns 145630.3333333333430346101522445678710937500000000000000000000
# # NOTE:
# will never show leading spaces or zeros
# as the decimal digit count is greater than the total digit count.

# So the way to calculate it what will properly be displayed is:
# `f"{VARIABLE:(TOTALDIGITS).(DECIMALDIGITS)f}"`
# Total Digits - Decimal Digits - 1 (for the decimal point)
# If the return from the equasion above is < 1 
# # There will never be a leading digit/space.  
# As shown in the last example of Digits & Decimals.  (16-55-1) =
# "-40"  So no Leading digits will ever show.

Digits Only

# If you only need to update formats for Digits and no Decimals:
a = 148
print(f"{a:016d}")
# or
print(f"{a:016.0f}")

# Returns 0000000000000148

print(f"{a:16d}")
# or 
print(f"{a:16.0f}")
# Returns "             148"

Exceptions to Note:

a = 148.15
print(f"{a:16d}")  # THROWS AN ERROR:
# ValueError: Unknown format code 'd' for object of type 'float'

# or 
print(f"{a:16.0f}")
# Returns "             148"
# # NOTE: This TRUNCATES YOUR DECIMAL FORMAT.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.