0

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?

The Pointer
  • 2,226
  • 7
  • 22
  • 50
  • 1
    `random.randbytes`? `secrets.token_bytes`? `os.urandom`? – Manuel Mar 20 '21 at 04:35
  • 1
    See [How much research](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) and the [Question Checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). – Prune Mar 20 '21 at 04:37
  • `bytes(choices(ascii_uppercase.encode(), k=12))`? – Manuel Mar 20 '21 at 04:50

2 Answers2

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

Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
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"))
Noah
  • 194
  • 1
  • 8