python用零填充小数 [英] python padding decimals with zeros

查看:178
本文介绍了python用零填充小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种用零填充浮点小数的方法:

I'm looking for a way to pad the float decimals with zeros:

这是我的参考资料

In [37]: '{:5.5}'.format(round(4.123456, 5))
Out[37]: '4.1235'

我有这个:

In [38]: '{:5.5}'.format(4.1)
Out[38]: '  4.1'

但是我想要这个:

Out[38]: '4.1000'

推荐答案

格式化具有给定精度的浮点数,您应该使用'f'说明符.没有它,该值将格式化为字符串.

To format a floating point number with a given precision you should use the 'f' specifier. Without it the value is formatted as a string.

>>> '{:.4f}'.format(4.1)
'4.1000

您还可以指定完整输出的最小宽度和填充字符:

You can also specify the minimum width of the complete output and the fill character:

>>> '{:07.4f}'.format(4.1)
'04.1000'

此处在输出的左侧用零填充,以至少包含7个字符.

Here the output is padded on the left with zeros to be at least 7 characters.

这篇关于python用零填充小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆