How to generate random number with the specific length in python

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

    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)
    

提交回复
热议问题