如何在 Python 中將數字格式化為字串?
可以使用 String 上的格式函式使用 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 中格式化數字的所有細微差別。
廣告