Random String generator python -
i made simple programme in python generate random string 5 numbers in it:
import random numcount = 5 fstring = "" num in range(19): #strings 19 characters long if random.randint(0, 1) == 1: x = random.randint(1, 26) x += 96 fstring += (chr(x).upper()) elif not numcount == 0: x = random.randint(0, 9) fstring += str(x) numcount -= 1 print(fstring) not hard, right? except 1 incredibly unusual thing: strings returns of random length. have run code several times, , here of results:
>>> ================================ restart ================================ >>> vqz99ha5der0ces4 >>> ================================ restart ================================ >>> 05ps0t86lozs >>> ================================ restart ================================ >>> e2qx8296xk >>> ================================ restart ================================ >>> m5x9k457qdnbpx i can't figure out what's going on... can point me in right direction?
you flip coin 19 times; 50 percent of time pick letter, other 50 percent pick digit, only 5 times. if nail number alternative more often, do not add together anything.
so build string up to 19 characters, can shorter. on average it'll 9.5 letters, , 5 digits.
only pick numbers if still have numbers pick:
import string import random numcount = 5 chars = [] num in range(19): #strings 19 characters long if numcount , random.random() < 0.5: chars.append(str(random.randint(0, 9))) numcount -= 1 else: chars.append(random.choice(string.ascii_uppercase)) fchars = ''.join(chars) demo:
>>> import string >>> import random >>> string.ascii_uppercase 'abcdefghijklmnopqrstuvwxyz' >>> numcount = 5 >>> chars = [] >>> num in range(19): #strings 19 characters long ... if numcount , random.random() < 0.5: ... chars.append(str(random.randint(0, 9))) ... numcount -= 1 ... else: ... chars.append(random.choice(string.ascii_uppercase)) ... >>> ''.join(chars) '3m6g97oehp6tgyronpv' >>> len(chars) 19 python python-3.x
No comments:
Post a Comment