我們如何對 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