5

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

Community
  • 1
  • 1
Tampa
  • 75,446
  • 119
  • 278
  • 425
  • 4
    This is **not** a duplicate of [python random string generation with upper case letters and digits](http://stackoverflow.com/questions/2257441/python-random-string-generation-with-upper-case-letters-and-digits). This question wants a random bytestring, whereas the other one wants a random character string with a limited character set. – phihag Jul 21 '12 at 15:29

2 Answers2

23
import os
rand_string = os.urandom(8)

Would create a random string that is 8 characters long.

Rapptz
  • 20,807
  • 5
  • 72
  • 86
5

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.

phihag
  • 278,196
  • 72
  • 453
  • 469