如何显示小于两位数字的所有数字的前导零?

1    →  01
10   →  10
100  →  100

当前回答

print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

打印:

01
10
100

其他回答

如果处理的数字是一位数或两位数:

‘0’+ str (number)黑帽子-2:铝还是‘0那0’.format (number)黑-2:铝

你可以使用str.zfill:

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

打印:

01
10
100

在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}")

它内置在python中,具有字符串格式

f'{number:02d}'
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted