如何在 Python 中格式化具有可变位数的数字? [英] How do I format a number with a variable number of digits in Python?

查看:41
本文介绍了如何在 Python 中格式化具有可变位数的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想显示数字 123,并在前面显示不同数量的填充零.

例如,如果我想以 5 位数字显示它,我会给我数字 = 5:

00123

如果我想以 6 位数字显示它,我会得到数字 = 6:

000123

我将如何在 Python 中执行此操作?

解决方案

有一个字符串方法叫做zfill:

<预><代码>>>>'12344'.zfill(10)0000012344

它将用零填充字符串的左侧以使字符串长度为 N(在本例中为 10).

Say I wanted to display the number 123 with a variable number of padded zeroes on the front.

For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:

00123

If I wanted to display it in 6 digits I would have digits = 6 giving:

000123

How would I do this in Python?

解决方案

There is a string method called zfill:

>>> '12344'.zfill(10)
0000012344

It will pad the left side of the string with zeros to make the string length N (10 in this case).

这篇关于如何在 Python 中格式化具有可变位数的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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