我们如何对 Python 数字进行基本的打印格式化?
您可以在字符串上使用 format 函数来格式化 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 中格式化数字的所有细微差别。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP