為了排版方便或者是輸出文件命名整潔,通常需要給數字前面補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'