我想通过将整数 n 传递到字符串格式化字段来将 pi 打印到 n 小数位。但是,这给了我一个错误。执行此操作的正确方法是什么?
我的代码:
from math import pi
def print_pi(n):
print(("%."+str(n)) % pi)
错误:
Traceback (most recent call last):
File "1.2.3.py", line 4, in <module>
print_pi(5)
File "1.2.3.py", line 3, in print_pi
print(("%."+str(n)) % pi)
ValueError: incomplete format
请您参考如下方法:
使用新的(实际上,现在相当旧)format 方法更清晰:
>>> fmtstr = "{:.{}f}".format(math.pi, 2)
>>> print(fmtstr)
3.14
>>> fmtstr = "{:.{}f}".format(math.pi, 10)
>>> print(fmtstr)
3.1415926536
漂亮整洁:
>>> def print_pi(n, pi=math.pi):
... print("{:.{}f}".format(pi, n))
...
>>> for i in range(10):
... print_pi(i)
...
3
3.1
3.14
3.142
3.1416
3.14159
3.141593
3.1415927
3.14159265
3.141592654
