How to generate random number with the specific length in python

前端 未结 8 2348
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 13:07

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

>>> random(3)
563

or

>>> random(5)
26748
>> random(2)
56
         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 13:41

    To get a random 3-digit number:

    from random import randint
    randint(100, 999)  # randint is inclusive at both ends
    

    (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
    

提交回复
热议问题