-1

I am using webpage to get data in hex to write serial modbus using python

Issue is that 0A in the string gets converted to \n.

How to stop this from happening?

rList = r'0106000600000AE9CC'
arr=str(rList)
arr = bytes.fromhex(rList)

print(arr)

Output:

b'\x01\x06\x00\x06\x00\x00\n\xe9\xcc'
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    The hex value of the character _is_ `0A`, Python is just displaying it as an escape character when displaying the byte string's representation. – martineau Mar 14 '21 at 09:20

3 Answers3

1

The repr() representation of a bytes object uses ASCII code points wherever possible. What this means is \x0A will be displayed as \n, because that's the ASCII code point for a newline.

More examples:
\x55 will be displayed as U,
\x5A will be displayed as Z,
\x0D will be displayed as \r,
you get the idea.

However, the data under the hood is still the same.

Don't worry about how the output string is displayed by the Python console—it's presumably more important to process its content.

Ayush
  • 1,510
  • 11
  • 27
  • issue is that i have to send command to modbus and it take commands like this: \x01\x06\x00\x06\x0a\xe9\xcc but what python sends is this: \x01\x06\x00\x06\\n\xe9\xcc – embeddedeng Mar 15 '21 at 08:38
  • I don't think that's true, the underlying data is as-is, untouched. If the data is `\x01\x06\x00\x06\x0a\xe9\xcc`, then what is SENT is `\x01\x06\x00\x06\x0a\xe9\xcc` and what is DISPLAYED on console is `\x01\x06\x00\x06\\n\xe9\xcc` – Ayush Mar 15 '21 at 11:05
0

Try this

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

Output:

\x01\x06\x00\x06\x00\x00\x0a\xe9\xcc
0

b symbol before string means you have a list of bytes. As you print it, python tries to decode bytes whenever possible to represent them in symbols for simplicity.

Byte b'\x0A' corresponds to decimal value 10, which is a newline symbol in ascii. That is why you get this symbol printed.

Under the hood your byte b'\x0A' has not been changed.

xmantas
  • 578
  • 5
  • 11