How to generate random number with the specific length in python

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

    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)]))
    

提交回复
热议问题