2

In Python 3x, is there a way to generate a random number of a fixed number of digits that could return a 0 in the first place or first two places? e.g. 005 or 059 rather than 5 and 59?

I am creating a game where players need to enter a randomly created 3 digit code (found elsewhere in the game). Ideally it would be chosen from 000 - 999.

random.randint(0,999) won't provide the output I am after.

The only solution I can come up with is long winded (generating 3 numbers between 0 and 9, converting to strings and combining) and I would like to know if there is a more direct method:

import random

digit1 = str(random.randint(0,9))
digit2 = str(random.randint(0,9))
digit3 = str(random.randint(0,9))

code = digit1 + digit2 + digit3

This method would allow me to then compare to the user's input code but I would like to generate the number directly if possible.

EDIT: To clarify, I'd like to know if there is a way to generate a number that is of a predetermined number of digits, that can have a '0' in one or more of the leading digits, without having to convert the number to a string in order to format. Nicest way to pad zeroes to string helps although I am not trying to print the random number, but rather compare it to a use input (e.g. '0560').

Community
  • 1
  • 1
Jeff Mitchell
  • 1,067
  • 1
  • 8
  • 16
  • 1
    http://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-string – FDinoff May 15 '15 at 04:39
  • The leading zeros are part of the string representation. Just pad to 3 characters according to the advice in the linked question. – Janne Karila May 15 '15 at 10:41
  • Numbers don't have "digits". The textual representation of a number has digits. If you want 3-digit randoms, then just get random numbers from 0 to 999, and put the leading zeros in when you convert them to text. – Lee Daniel Crocker May 15 '15 at 19:35

1 Answers1

2

You can try the following:

import random

min = 0
max = 999
digits = [str(random.randint(min, max)) for i in range(5)]
digits = [(len(str(max))-len(digit))*'0'+digit for digit in digits]

>>> digits
['099', '142', '684', '881', '734']
>>> 
user1823
  • 1,111
  • 6
  • 19