How to generate a random number with a specific amount of digits?
Solution 1:
You can use either of random.randint
or random.randrange
. So to get a random 3-digit number:
from random import randint, randrange
randint(100, 999) # randint is inclusive at both ends
randrange(100, 1000) # randrange is exclusive at the stop
* Assuming you really meant three digits, rather than "up to three digits".
To use an arbitrary number of digits:
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
print random_with_N_digits(2)
print random_with_N_digits(3)
print random_with_N_digits(4)
Output:
33
124
5127
Solution 2:
If you want it as a string (for example, a 10-digit phone number) you can use this:
n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
Solution 3:
If you need a 3 digit number and want 001-099 to be valid numbers you should still use randrange/randint as it is quicker than alternatives. Just add the neccessary preceding zeros when converting to a string.
import random
num = random.randrange(1, 10**3)
# using format
num_with_zeros = '{:03}'.format(num)
# using string's zfill
num_with_zeros = str(num).zfill(3)
Alternatively if you don't want to save the random number as an int you can just do it as a oneliner:
'{:03}'.format(random.randrange(1, 10**3))
python 3.6+ only oneliner:
f'{random.randrange(1, 10**3):03}'
Example outputs of the above are:
- '026'
- '255'
- '512'
Implemented as a function that can support any length of digits not just 3:
import random
def n_len_rand(len_, floor=1):
top = 10**len_
if floor > top:
raise ValueError(f"Floor '{floor}' must be less than requested top '{top}'")
return f'{random.randrange(floor, top):0{len_}}'