Python: How to generate a 12-digit random number?

前端 未结 6 1377
予麋鹿
予麋鹿 2021-01-04 03:39

In Python, how to generate a 12-digit random number? Is there any function where we can specify a range like random.range(12)?

import random
ran         


        
6条回答
  •  余生分开走
    2021-01-04 04:24

    Do random.randrange(10**11, 10**12). It works like randint meets range

    From the documentation:

    randrange(self, start, stop=None, step=1, int=, default=None, maxwidth=9007199254740992L) method of random.Random instance
        Choose a random item from range(start, stop[, step]).
    
        This fixes the problem with randint() which includes the
        endpoint; in Python this is usually not what you want.
        Do not supply the 'int', 'default', and 'maxwidth' arguments.
    

    This is effectively like doing random.choice(range(10**11, 10**12)) or random.randint(10**1, 10**12-1). Since it conforms to the same syntax as range(), it's a lot more intuitive and cleaner than these two alternatives

    If leading zeros are allowed:

    "%012d" %random.randrange(10**12)
    

提交回复
热议问题