格式 () :值错误:整数格式说明符中不允许的精度



我是python新手。我刚刚熟悉格式方法。

从我正在阅读的学习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')

在python解释器中,如果我尝试

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

它给出了错误

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

最好添加f

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

通过这种方式,您可能会注意到1/3给出了一个整数,然后将其更正为 1./31/3.

要打印浮点数,您必须至少有一个输入作为浮点数,如下所示

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

如果两个输入都是除法运算符的整数,则返回的结果也将采用 int,小数部分将被截断。

输出

0.333

您可以使用float函数将数据转换为浮点数,如下所示

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

值得注意的是,此错误只会发生在python 2中。 在 python 3 中,除法总是返回一个浮点数。

您可以使用 python 2 中的 from __future__ import division 语句复制这一点。

~$ 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'

Python3 fstring 示例:

小数

# 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

数字和小数

# 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.

仅数字

# 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"

需要注意的例外情况:

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.

最新更新