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.
You need to encode the string to be able to convert it to bytes:
string = "b0x340xEF".encode("latin-1")
print(string)
Output:
b'b0x340xEF'
bytes call is superflous; string is already a bytes object (though its name is then misleading)..encode("us-ascii") would probably be more correct. For any actually useful example, UTF-8 is almost certainly the wrong encoding."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.