When I execute this code:
month = random.randint(1, 12)
and I get a number below 10, its without a 0 at the start. For an example, it generates 5. I don't want it to be 5, I want it to be 05
How would I do this?
CodePudding user response:
Try this:
# below code generate random number between [1,12]
rnd_int = random.randint(1, 12)
# And If you want until '10' change to this:
# rnd_int = random.randint(1, 10)
if len(str(rnd_int))==1:
rnd_int = '0' str(rnd_int)
print(rnd_int)
One random output: 02
CodePudding user response:
try this it is nice and short.
i = 5
print(f"{i:02}")
output:
05
CodePudding user response:
You can use str.zfill()
here.
num = random.randint(1, 12)
num = str(num).zfill(2)
print(num)
05
CodePudding user response:
You can do like this,
print(f"{random.randint(1, 12):02}")
Execution:
In [1]: print(f"{random.randint(1, 12):02}")
11
In [2]: print(f"{random.randint(1, 12):02}")
02
In [3]: print(f"{random.randint(1, 12):02}")
10
In [4]: print(f"{random.randint(1, 12):02}")
01