>>> '{:04d}'.format(16/2)
'0008'
Run Code Online (Sandbox Code Playgroud)
字符串格式04d表示:
0 -- fill spaces with 0
4 -- width should be 4 (though can be greater if the input requires it)
d -- format the input as an integer
Run Code Online (Sandbox Code Playgroud)
有关格式字符串语法的详细信息,请参阅此页面.
str.zfill() 更适合这个:
>>> str(16/2).zfill(4)
'0008'
Run Code Online (Sandbox Code Playgroud)
str.zfill(width)返回长度的串填充零的数字串左宽度.正确处理符号前缀.如果width小于或等于,则返回原始字符串
len(s).