简体   繁体   中英

Python Hex-String to Hex-String with Backslash

I'm really confused, with Byte-Strings in Python.

I need to compare two Byte-Strings, so they should be converted the same (?)

I have a String of Hex-Values:

52fab71f49a01ef92e793b41c13c5458080679919c7e5888f195935bd50c1bb8

If I convert this to a Byte-String with bytes.fromHex('52fab...') I get:

b'R\xfa\xb7\x1fI\xa0\x1e\xf9.y;A\xc1<TX\x08\x06y\x91\x9c~X\x88\xf1\x95\x93[\xd5\x0c\x1b\xb8'

But I want the 'R' at the beginning as '0x52' . How can I achieve this?
Why do I get 'R' instead of '0x52' ? As Example, for the 2nd Byte, I get '0xfa' for 'fa' .

Same Problem with the other Ascii "Letter" like 'y', ';', 'A'...

I hope this is not too confusing - I haven't found a appropriate solution after a long research.

Greetings

Daniel

You can't.

If you're using the standard bytes type, that's what its string representation is going to look like: it will represent all ASCII characters as themselves. For example, b'\x42' is the ASCII 'R' character, so it'll be printed as itself.

Of course, you can create your own function to get the output you want, like:

def print_me(thing: bytes):
    print(''.join(
        f'\\x{byte:02x}'
        for byte in thing
    ))

>>> print_me(bytes.fromhex("52fab71f49a01ef92e793b41c13c5458080679919c7e5888f195935bd50c1bb8"))
\x52\xfa\xb7\x1f\x49\xa0\x1e\xf9\x2e\x79\x3b\x41\xc1\x3c\x54\x58\x08\x06\x79\x91\x9c\x7e\x58\x88\xf1\x95\x93\x5b\xd5\x0c\x1b\xb8

but the underlying data stored in your bytes object will still be the same, no matter how you represent it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM