数字01的Python脚本错误

时间:2016-08-18 20:52:35

标签: python

我有以下脚本,似乎有错误:

import random, time
from random import randint

while True:
    part_1 = randint(1,31)
    part_2 = randint(1,12)
    part_3 = random.choice([81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,00,01,02,03,04])

    if part_3 == 01 or part_3 == 1:
        part_3 = 0 + part_3
    full = str(part_1) + " " + str(part_2) + " " + str(part_3)
    print full
    time.sleep(1)

在part_3中,我想让它成为01,但它只是打印为1.我想要与2,3等相同的行为。我该怎么做?

2 个答案:

答案 0 :(得分:2)

full的声明更改为:

full = "%02d %02d %02d" % (part_1, part_2, part_3)

您可以阅读有关格式字符串here的更多信息。

答案 1 :(得分:0)

使用str.format

的替代答案
part_1 = randint(1,31)
part_2 = randint(1,12)
part_3 = random.choice([81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,00,01,02,03,04])

full = ('{:02d} '*3).format(part_1, part_2, part_3).rstrip() 
# '16 09 97'