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

1

2 Answers 2

23
import os
rand_string = os.urandom(8)

Would create a random string that is 8 characters long.

Sign up to request clarification or add additional context in comments.

1 Comment

No, it creates a string that is 8 bytes long. "Characters" is a matter of interpretation.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.