How to generate random number with the specific length in python

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

    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
    

提交回复
热议问题