Possible Duplicate:
python random string generation with upper case letters and digits
I need to create a random string that is 8 bytes long in python.
rand_string = ?
How do I do that?
Thanks
import os
rand_string = os.urandom(8)
Would create a random string that is 8 characters long.
os.urandom
provides precisely this interface.
If you want to use the random
module (for deterministic randomness, or because the platform happens to not implement os.urandom
), you'll have to construct the function yourself:
import random
def randomBytes(n):
return bytearray(random.getrandbits(8) for i in range(n))
In Python 3.x, you can substitute bytearray
with just bytes
, but for most purposes, a bytearray
should behave like a bytes
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With