Leif160519的blog Leif160519的blog

——————

目录
Python自动给数字前面补0
/  

Python自动给数字前面补0

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

n = "123"
s = n.zfill(5)
assert s == '00123'

zfill也可以给负数补0:

n = "-123"
s = n.zfill(5)
assert s == '-0123'

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

n = 123
s = '%05d' % n
assert s == '00123'

“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” – Tom Cargill

标  题Python自动给数字前面补0
作  者Leif160519
出  处https://github.icu/articles/2019/10/08/1570521151777.html
关于博主:坐标南京,运维工程师,如有问题探讨可以直接下方留言。
声援博主:如果您觉得文章对您有帮助,可以评论、订阅、收藏。您的鼓励是博主的最大动力!