How to generate random numbers in python having(11 to 20 digits) that should not start with 0 in beginning?
eg:23418915901
def key_more_than_10():
v=random.randint(11,20)
char_set = string.digits+string.digits+string.digits
s= ''.join(random.sample(char_set,v))
return s
I used this code but since string.digits(give numbers between 0 to 9) it doesnt help me?
There should be an equal possibility to have 11 digits number and a 20 digits number.
Simple:
>>> help(random.randint)
Help on method randint in module random:
randint(self, a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
>>> random.randint(10000000000,99999999999999999999)
35677750742418249489
Of course, if you actually want a string (not sure why you would), you could wrap a str()
around the whole thing:
>>> str(random.randint(1000000000,99999999999999999999))
'91138793919270489115'
How about a literal translation of what you want into code:
import random
DIGITS = '0123456789'
ndigits = random.randint(11, 20)
digits = [random.choice(DIGITS[1:])] + [random.choice(DIGITS) for i in xrange(ndigits-1)]
print int(''.join(digits))
The number of digits in the almost random result should be uniformly distributed between 11..20. Not quite random because restricting the first digit to a something other than a zero precludes it.
I would choose randrange for this
Help on method randrange in module random: randrange(self, start, stop=None, step=1, int=<type '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.
so
random.randrange(1e11, 1e20)
will do what you want. For a string use this
str(random.randrange(1e11, 1e20))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.