Python integer formatting

我的梦境 提交于 2021-01-02 05:49:49

问题


I was wondering if it's possible to use two format options together when formatting integers.

I know I can use the bellow to include zero places

varInt = 12

print(
    "Integer : " +
    "{:03d}".format(varInt)
)

To get the output "Integer : 012"

I can use the following to include decimal places

varInt = 12

print(
    "Integer : " +
    "{:.3f}".format(varInt)
)

To get the output "Integer : 12.000"

But is it possible to use them both together to get the output "Integer : 012.000"


回答1:


varInt = 12

print(
    "Integer : " +
    "{:07.3f}".format(varInt)
)

Outputs:

Integer : 012.000

The 7 is total field width and includes the decimal point.




回答2:


Sure, the number at the beginning is the minimum length of the outputted string, so include the decimal part and the decimal point as well.

>>> "{:07.3f}".format(12)
'012.000'



回答3:


Not only can you specify the minimum length and decimal points like this:

"{:07.3f}".format(12)

You can even supply them as parameters like this:

"{:0{}.{}f}".format(12, 7, 3)


来源:https://stackoverflow.com/questions/32013276/python-integer-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!