How to generate random number with the specific length in python

前端 未结 8 2391
被撕碎了的回忆
被撕碎了的回忆 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:21

    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.

提交回复
热议问题