Print bytes to hex

后端 未结 2 350
-上瘾入骨i
-上瘾入骨i 2020-12-21 21:00

I want to encode string to bytes.

To convert to byes, I used byte.fromhex()

>>> byte.fromhex(\'7403073845\')
b\'t\\x03\\x078E\'         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-21 21:59

    The Python repr can't be changed. If you want to do something like this, you'd need to do it yourself; bytes objects are trying to minimize spew, not format output for you.

    If you want to print it like that, you can do:

    from itertools import repeat
    
    hexstring = '7403073845'
    
    # Makes the individual \x## strings using iter reuse trick to pair up
    # hex characters, and prefixing with \x as it goes
    escapecodes = map(''.join, zip(repeat(r'\x'), *[iter(hexstring)]*2))
    
    # Print them all with quotes around them (or omit the quotes, your choice)
    print("'", *escapecodes, "'", sep='')
    

    Output is exactly as you requested:

    '\x74\x03\x07\x38\x45'
    

提交回复
热议问题