-3

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?

  • Your question is about adding leading zeroes, check [this answer](https://stackoverflow.com/a/134951/14507110) – Billy Apr 06 '22 at 13:45
  • You are generating integers ... not strings. Integers have no leading zeros ... unless you a) format them when printing or b) convert them to string and print that with leading zeros – Patrick Artner Apr 06 '22 at 13:46

4 Answers4

0

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

jeandemeusy
  • 226
  • 3
  • 12
0

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}")
Dj0ulo
  • 440
  • 4
  • 9
  • 1
    From Python 3.6+ you can use f-strings instead of the `%` formatting operator, it is highly encouraged – Billy Apr 06 '22 at 13:49
0

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}")
OctopuSS7
  • 465
  • 2
  • 9
-1
len = 3-len(str(ran))
for x in range(0, len):
    ran = "0" + ran
print (ran)