[Python - Basic] 利用zfill方法自动给数字前面补0

python中有一个zfill方法用来给字符串前面补0,非常有用
Python zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
语法格式:str.zfill(width),width指定字符串的长度

 1 #view sourceprint?
 2 n = "123"
 3 s = n.zfill(5) 
 4 assert s == "00123"
 5 
 6 # zfill()也可以给负数补0
 7 n = "-123"
 8 s = n.zfill(5) 
 9 assert s == "-0123"
10 
11 #对于纯数字,我们也可以通过格式化的方式来补0
12 n = 123
13 s = "%05d" % n 
14 assert s == "00123"

 

posted @ 2021-11-26 23:40  决明子~  阅读(145)  评论(0编辑  收藏  举报