3

With the following script:

data = "000102030405060708090a0b0c0d0e0f"
data = bytes(bytearray.fromhex(data))
print(data)

I get:

b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

What I would like to get:

b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'

I am coding in Python 3.x, and I just can't figure this out.

Jim Stewart
  • 16,964
  • 5
  • 69
  • 89
G. Boar
  • 31
  • 2
  • It's not quite clear what your goal is-- those two bytestrings are exactly the same, and there's no way to change the default representation. Do you want to build a *string* (note, not a bytes object) which always uses the hex instead? – DSM Nov 27 '16 at 22:15
  • I am using Python ZigBee module to communicate with a micro controller via UART. The module only takes exact hex representation. I was hoping there was a quick fix for this. – G. Boar Nov 27 '16 at 22:23
  • But `b"\t"` and `b"\x09"` are *exactly the same byte*. Your module either accepts the raw bytes (which is what I'd expect, and in which case you're fine), or it accepts a *string* (probably of ascii hex characters), in which case what you want to have wouldn't help you anyway, or something else, in which case we'd need to know what that is. – DSM Nov 27 '16 at 22:38
  • The module accepts bytes, but for some reason it would only take b'\x09' and not b'\t'. – G. Boar Nov 27 '16 at 22:49
  • That's very hard to believe -- type `b'\x09'` at the console, and you get `b'\t'` out, because they're exactly the same byte, just being shown differently. It's like `13.0` vs `13.00` -- they're exactly the same float. It's more likely that something else changed, but this is now an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – DSM Nov 27 '16 at 22:52
  • Thank you DSM. I did I few tests, and now it works. Not sure what caused the original crash. – G. Boar Nov 27 '16 at 22:59

1 Answers1

1

The underlying bytes representation of your data object remains valid, no matter what it printed. But if printing is specifically what you're after, you can work it around with something like that:

>>> print("".join("\\x{:02x}".format(c) for c in data))
\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f

I don't think you can force bytes.__repr__() to print printable ASCII characters as hex values.

Michał Góral
  • 1,439
  • 2
  • 16
  • 30