0

I need the a string to be converted to bytes exactly as it is, so it would look like b and binascii.hexlify() would be the same for both a and b. Best way to do it? Python 3.10.0

a = "\x8e"
b = b'\x8e'
print(bytes(a, 'utf-8')) # b'\xc2\x8e'
print(b) # b'\x8e'
print(binascii.hexlify(bytes(a, 'utf-8'))) # b'c28e'
print(binascii.hexlify(b)) # b'8e'
Sandpaw
  • 23
  • 7
  • https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3 - `my_str_as_bytes = str.encode(my_str)` – Larry the Llama Dec 04 '21 at 05:32
  • `\x8e` is outside of the ASCII range of 7 bits. This means it is a matter of encodings and code pages how this translates to bytes. This is why strings and bytes got separated in Python 3. Use the right on for your purpose (bytes)! – Klaus D. Dec 04 '21 at 05:35
  • It makes b'\xc2\x8e', I want it to be b'\x8e'. Also, why does it add \xc2? – Sandpaw Dec 04 '21 at 05:35

1 Answers1

0
a = r'\x8e'
exec('my_string = b"' + a + '"')
print(my_string)

That does it.

Sandpaw
  • 23
  • 7