format():ValueError:整数格式说明符中不允许使用精度。

15

我是一名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 
4个回答

13

最好添加f

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

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


12

要打印浮点数,您必须将至少一个输入设置为浮点数,就像这样

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

如果除数和被除数均为整数,则返回的结果也将是整数,小数部分将被舍去。

输出

0.333
你可以使用float函数将数据转换为浮点数,像这样。
data = 1
print('{0:.3}'.format(float(data) / 3))

1
"{0:.3}" 是什么意思?格式化如何替换这些值? - liv2hak
@liv2hak,在格式函数中,0是第一个参数。冒号只是传递数据元素和格式化之间的分隔符。.3表示将其格式化为小数点右侧3个字符。 - John

5
值得注意的是,这个错误只会在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'

1

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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接