ran = random.randint(1,999)
print(ran)
some times the output comes as 45 or 5 but I want it to be 045 or 005, how do i do that?
ran = random.randint(1,999)
print(ran)
some times the output comes as 45 or 5 but I want it to be 045 or 005, how do i do that?
you can use python formatter:
print(f"{ran:03d}")
This will print the number with leading 0's so that it takes 3 characters.
See this also: Display number with leading zeros
This question has already been answered here.
In Python 2 (and Python 3) you can do:
print("%03d"%ran)
In Python 3.6+, you can use f-strings like this:
print(f"{ran:03d}")
A number can't have leading zeros in python but a string can, so you would generate random numbers then add the leading zeros as a string.
from random import randint
ran = random.randint(1,999)
print(f"{ran:02d}")
len = 3-len(str(ran))
for x in range(0, len):
ran = "0" + ran
print (ran)