python 在数字前面自动补0

1. 为了排版方便或者是输出文件命名整洁,通常需要给数字前面补0来做统一。 Python中有一个zfill函数用来给字符串前面补0,非常有用,这个zfill看起来也就是zero fill的缩写吧,看一下如何使用:

代码示例:

n = "345"
s = n.zfill(6)
print(s)

运行结果:

000345

2.zfill也可以给负数补0:

代码示例:

n = '-123'
s = n.zfill(5)
print(s)

运行结果:

-0123

3.对于纯数字也可以通过格式化的方式来补0:

代码示例:

n = 123
s = '%05d' % n
print(s)

运行结果:

00123

参考文章:
python自动给数字前面补0的方法

发布了140 篇原创文章 · 获赞 51 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_38819889/article/details/103022565