'Adding single backslash to binary string in python

Am communicating with a piece of equipment over RS232, and it seems to only interpret commands correctly when issued commands in the following format:

b'\xXX'

for example:

equipment_ser.write(b'\xE1')

The argument is variable, and so I convert to hex before formatting the command. I'm having trouble coming up with a consistent way to ensure only 1 backslash while preserving the hex command. I need the entire range - \x00 to \xFF.

One approach was to use 'unicode escape':

    setpoint_command_INT = 1

    setpoint_command_HEX = "{0:#0{1}x}".format(setpoint_command_INT,4)
    
    setpoint_command_HEX_partially_formatted = r'\x' + setpoint_command_HEX[2:4]

    setpoint_command_HEX_fully_formatted = setpoint_command_HEX_partially_formatted.encode('utf_8').decode('unicode_escape')

works ok for the above example:

Out[324]: '\x01'

but not for large numbers where the code process changes it:

setpoint_command_INT = 240

Out[332]: 'ð'

How can I format this command so that I have the single backslash while preserving the ability to command across the full range 0-255?

Thanks

Edit:

The correct way to do this is as said by Michael below:

bytes((240,))

Thank you for the prompt responses.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source