Writing the hexadecimal indication '\x' only, while avoiding “ValueError: invalid \x escape”

时间:2017-05-16 09:20:36

标签: python python-3.x bytestring

There are a lot of posts about the error message ValueError: invalid \x escape, however, I am still stuck, although it's a simple problem. I am trying to build a bytestring line out of different building blocks. In the end it has to look like:

b'Kh\x10\x10\x10'

so two ascii symbols at the beginning and three hexadecimal values. I already have the K (from dict_birdnumbers[int(birdname)]) and the '10' (finangle) as variables. I tried it with a raw literal string

hex = r'\x'
line3 =  dict_birdnumbers[int(birdname)] + 'h' + hex + finangle + hex + finangle + hex + finangle
print(line3.encode()) 

I use the .encode() to ensure that it's a bytestring. However, the result I get is

b'Kh\\x10\\x10\\x10'

so one backslash too much. If I delete the backslash in hex I only get b'Khx10x10x10' . If I use a normal string like hex = '\x' I get the error message ValueError: invalid \x escape. What can I do?

1 个答案:

答案 0 :(得分:1)

\xhh is a notation; each \xhh sequence creates one character. You can't concatenate \x and two hex digits to get the same effect.

Instead, just pass a sequence of integers to bytes():

finagle = int(finangle, 16)  # assuming finagle is a hex notation string
line3 =  b'%sh%s' % (
    dict_birdnumbers[int(birdname)].encode('ascii'),
    bytes([finangle, finangle, finangle])
)

This creates a bytes object with 3 bytes, each with integer value 16, hex value 10. The repr() output of bytes happens to use \xhh to display such bytes because the alternative is not really printable (this is done for all non-printable byte values, those outside of the printable ASCII range):

>>> bytes([0x10, 0x10, 0x10])  # 3 integers using hex syntax
b'\x10\x10\x10'