如何显示小于两位数字的所有数字的前导零?
1 → 01
10 → 10
100 → 100
如何显示小于两位数字的所有数字的前导零?
1 → 01
10 → 10
100 → 100
当前回答
Use:
'00'[len(str(i)):] + str(i)
或者使用数学模块:
import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
其他回答
或:
打印“{0:02d}”.format (1)
在Python 2(和Python 3)中,您可以执行:
number = 1
print("%02d" % (number,))
基本上%类似于printf或sprintf(参见文档)。
对于Python 3。+,同样的行为也可以通过format实现:
number = 1
print("{:02d}".format(number))
对于Python 3.6+,同样的行为可以通过f-strings实现:
number = 1
print(f"{number:02d}")
Use:
'00'[len(str(i)):] + str(i)
或者使用数学模块:
import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
使用格式字符串- http://docs.python.org/lib/typesseq-strings.html
例如:
python -c 'print "%(num)02d" % {"num":5}'
在Python >= 3.6中,您可以使用以下方法引入的新f-string简单地完成此操作:
f'{val:02}'
它输出名为val的变量,填充值为0,宽度为2。
对于你的具体例子,你可以在循环中很好地做到这一点:
a, b, c = 1, 10, 100
for val in [a, b, c]:
print(f'{val:02}')
打印:
01
10
100
有关f-字符串的更多信息,请参阅PEP 498,其中介绍了f-字符串。