Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how to create a random string 8 bytes long? [duplicate]

Tags:

python

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

like image 325
Tampa Avatar asked Jul 21 '12 15:07

Tampa


2 Answers

import os
rand_string = os.urandom(8)

Would create a random string that is 8 characters long.

like image 137
Rapptz Avatar answered Oct 14 '22 11:10

Rapptz


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.

like image 31
phihag Avatar answered Oct 14 '22 09:10

phihag