2

I am able to define a bytes string as follows:

string = b"0x340xEF"

I want to cast an already made string. Let us call it string into a bytes string. How do I perform this? bytes(string) is not giving me an equivalent result.

Cardstdani
  • 4,999
  • 3
  • 12
  • 31

1 Answers1

2

You need to encode the string to be able to convert it to bytes:

string = "b0x340xEF".encode("latin-1")
print(string)

Output:

b'b0x340xEF'
Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • 3
    The `bytes` call is superflous; `string` is already a `bytes` object (though its name is then misleading). – tripleee Jul 01 '22 at 10:49
  • 1
    The question simply uses an ASCII string, so using `.encode("us-ascii")` would probably be more correct. For any actually useful example, UTF-8 is almost certainly the wrong encoding. – tripleee Jul 01 '22 at 10:51
  • @tripleee: Plain `"ascii"` is the standard name (it's optimized to avoid actual codec lookup if you use that name). That said, if you want straight one-to-one mapping from any byte to Unicode characters with equivalent ordinals and back, `"latin-1"` provides that. – ShadowRanger Jul 01 '22 at 10:53