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.

0

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

3 Comments

The bytes call is superflous; string is already a bytes object (though its name is then misleading).
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: 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.