161

Let's say I need a 3-digit number, so it would be something like:

>>> random(3)
563

or

>>> random(5)
26748
>> random(2)
56
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Arty
  • 5,923
  • 9
  • 39
  • 44

11 Answers11

263

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
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • 7
    With this solution, you will eliminate 10**(n-1) numbers from your random pool – Nicu Surdu Feb 03 '12 at 13:29
  • 7
    @NicolaeSurdu: Yes, that's why I said *assuming you really meant three digits, rather than "up to three digits".* – RichieHindle Feb 03 '12 at 15:39
  • 3
    037 it's a 3 digit number, smaller than 100 :). That's what I meant. But yeah, for a non-lottery application, your solution is just fine ;) – Nicu Surdu Feb 07 '12 at 15:12
  • @NicolaeSurdu How can this snipet give you a result of 037??? it's a randint from (100 to 1000) if n ==3 – moldovean Jan 07 '14 at 10:17
  • 3
    @moldovean Read from the top :). I meant I wanted that number and this solution will not give you numbers up to that number of digits but rather of exactly that number of digits. It was my bad, I missed the clause in the parenthesis. – Nicu Surdu Jan 07 '14 at 12:19
  • This really should just be random.randit(0,999) Otherwize you can have "909" and "990" but not "099". – J.J Jan 15 '16 at 20:12
  • @J.J: Yes, that's why I said *assuming you really meant three digits, rather than "up to three digits"*. Please read the previous comments. – RichieHindle Jan 15 '16 at 21:51
  • @J.J: Up to three digits is easier `'{:03}'.format(random.randrange(0, 10**n))`. – Brian Nov 27 '17 at 06:27
  • 1
    Also possible is `"".join([str(randint(0, 9)) for i in range(n)])` or something to this degree. – Shmack Oct 22 '21 at 21:39
56

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)])
Human
  • 726
  • 8
  • 27
osman
  • 1,590
  • 1
  • 14
  • 21
27

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_}}'
Brian
  • 987
  • 10
  • 19
7

You could write yourself a little function to do what you want:

import random
def randomDigits(digits):
    lower = 10**(digits-1)
    upper = 10**digits - 1
    return random.randint(lower, upper)

Basically, 10**(digits-1) gives you the smallest {digit}-digit number, and 10**digits - 1 gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.

Daniel G
  • 67,224
  • 7
  • 42
  • 42
6

Does 0 count as a possible first digit? If so, then you need random.randint(0,10**n-1). If not, random.randint(10**(n-1),10**n-1). And if zero is never allowed, then you'll have to explicitly reject numbers with a zero in them, or draw n random.randint(1,9) numbers.

Aside: it is interesting that randint(a,b) uses somewhat non-pythonic "indexing" to get a random number a <= n <= b. One might have expected it to work like range, and produce a random number a <= n < b. (Note the closed upper interval.)

Given the responses in the comments about randrange, note that these can be replaced with the cleaner random.randrange(0,10**n), random.randrange(10**(n-1),10**n) and random.randrange(1,10).

Andrew Jaffe
  • 26,554
  • 4
  • 50
  • 59
  • @Andrew: `a <= n <= b` surprised me too. I resent having to put that extra `-1` in my code. :-) – RichieHindle Apr 20 '10 at 07:53
  • 1
    @Andrew - funnily enough, the Python code for `randint` (it's in Lib/random.py) actually just calls `randrange(a, b+1)`! – Daniel G Apr 20 '10 at 07:55
4
import random

fixed_digits = 6 

print(random.randrange(111111, 999999, fixed_digits))

out:
271533
jeevu94
  • 477
  • 4
  • 16
1

You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:

import random

def generate_random_number(length):
    return int(''.join([str(random.randint(0,10)) for _ in range(length)]))
Andre Machado
  • 316
  • 2
  • 3
0

I really liked the answer of RichieHindle, however I liked the question as an exercise. Here's a brute force implementation using strings:)

import random
first = random.randint(1,9)
first = str(first)
n = 5

nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs))    :
    first += str(nrs[i])

print str(first)
moldovean
  • 3,132
  • 33
  • 36
0

From the official documentation, does it not seem that the sample() method is appropriate for this purpose?

import random

def random_digits(n):
    num = range(0, 10)
    lst = random.sample(num, n)
    print str(lst).strip('[]')

Output:

>>>random_digits(5)
2, 5, 1, 0, 4
kerwei
  • 1,822
  • 1
  • 13
  • 22
0

I know it's an old question, but I see many solutions throughout the years. here is my suggestion for a function that creates an n digits random string with default 6.

from random import randint

def OTP(n=6):
    n = 1 if n< 1 else n
    return randint(int("1"*n), int("9"*n))

of course you can change "1"*n to whatever you want the start to be.

Elie Saad
  • 516
  • 4
  • 8
0

I think the best option is to use this

from string import digits
import random

verify_code = ''.join(random.choice(digits) for i in range(6))
Taymoor Q.
  • 1,371
  • 21
  • 33