![]() Enforce amount of digits/upper characters etcġ07 µs ± 11.9 µs per loop (mean ± std. In this case, it actually simplifies to gerrit's answer (but then you loose the finer-grained control): import stringġ.62 µs ± 96.6 ns per loop (mean ± std. If considered speed, you can also drop the while-loop. If (sum(c.islower() for c in password) >=4Īnd sum(c.isupper() for c in password) >=4Īnd sum(c.isdigit() for c in password) >=4):ģ. Password = ''.join(secrets.choice(alphabet) for i in range(20)) ![]() In this example, there are just - and _ added.Īlphabet = string.ascii_letters + string.digits + '-_' Special characters can be added to alphabet.Forcing at least 4 upper case characters.Forcing at least 4 lower case character.Of course, this is not fast option if you need to generate a lot of passwords. With this you have more fine grained control on how to generated passwords have to look. This is slighly modified copy from the docs of secrets. Enforce amount of digits/upper characters etc On average, one byte is 1.3 characters (base64 encoded). The argument for token_urlsafe is number of bytes. ![]() (see timings below) import secretsĮxample output: 4EPn9Z7RE3l6jtC圎y7CPhia2EnYDEkE6N1O3-WnntU This is much faster than the accepted answer. Two recipes using the builtin secrets (python 3.6+) 1. So, the winner is ''.join(choice(chars) for _ in xrange(length)). ''.join(map(lambda x: random.choice(chars), range(length))) # way 5 2.27 seconds ''.join(choice(chars) for _ in xrange(length)) # way 4 1.73 seconds ''.join(choice(chars) for _ in range(length)) # way 3 1.8 seconds ''.join() # way 2 1.8 seconds (optimizer helps?) So here we are with some testing with timeit for 100000 iterations: ''.join(sample(chars,length)) # way 1 2.5 seconds
0 Comments
Leave a Reply. |