-1

I want to generate a random byte string of length n in Python. For example, I want byte strings such as b"helloworld" generated. This answer gives the following code for generating random strings:

from random import choice
from string import ascii_uppercase

print(''.join(choice(ascii_uppercase) for i in range(12)))

However, this just generates strings and not byte strings.

How do I do this?

3
  • 1
    random.randbytes? secrets.token_bytes? os.urandom? Commented Mar 20, 2021 at 4:35
  • 1
    See How much research and the Question Checklist. Commented Mar 20, 2021 at 4:37
  • bytes(choices(ascii_uppercase.encode(), k=12))? Commented Mar 20, 2021 at 4:50

2 Answers 2

3

Just chain encode() method after your join() method:-

print(''.join(choice(ascii_uppercase) for i in range(12)).encode())

Note:- if you want to encode in some specific encoding then pass that encoding as parameter in encode() method

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

Comments

2

simply encode() it.

from random import choice
from string import ascii_uppercase

test = ''.join(choice(ascii_uppercase) for i in range(12))
print(test.encode("utf-8"))

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.