如何在 Python 中将数字格式化为字符串?

pythonprogrammingserver side programming

您可以使用字符串上的格式函数将浮点数格式化为 Python 中的固定宽度。

示例

nums = [0.555555555555, 1, 12.0542184, 5589.6654753]
for x in nums:
   print("{:10.4f}".format(x))

输出

这将给出输出 −

0.5556
1.0000
12.0542
5589.6655

示例

使用相同的函数,您还可以格式化整数 −

nums = [5, 20, 500]
for x in nums:
   print("{:d}".format(x))

输出

将给出输出 −

5
20
500

示例

您也可以使用它来提供填充,方法是在 d 之前指定数字:

nums = [5, 20, 500]
for x in nums:
   print("{:4d}".format(x))

输出

这将给出输出 −

5
20
500

https://pyformat.info/ 网站是学习 Python 中数字格式所有细节的绝佳资源。


相关文章