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'

参考: http://www.sharejs.com/codes/python/8037

原文地址:https://www.cnblogs.com/yibeimingyue/p/13769788.html