Arzybek
Arzybek

Reputation: 802

Why does bytes.fromhex() produce the output shown?

I was wondering why this hex: bytes.fromhex("34 FF FA A3 A5") gives an output: b'4\xff\xfa\xa3\xa5'. Why \x disappeared, shouldn't it be \x34?

Upvotes: 1

Views: 1497

Answers (2)

Pouya Esmaeili
Pouya Esmaeili

Reputation: 1263

Python tries to print a good looking equivalent. In your case we have: '0x34'= hex(ord("4")) , which means Unicode integer representing of 4 in hex equals '0x34'. Try this one in your console: print ("\x09") . That's because \x09 in hex format represents \t.

Upvotes: 1

ShadowRanger
ShadowRanger

Reputation: 155448

That's how bytes reprs work; when a byte has an ordinal value corresponding to a printable ASCII character, it's represented as the ASCII character, rather than the \x escape code. You can create the bytes with either form (b'4' == b'\x34' is True; they produce the exact same bytes value), but it chooses the ASCII display to make byte strings that happen to be ASCII more readable (and make many reprs shorter).

Upvotes: 3

Related Questions