Python Forum

Full Version: Python Struct Question, decimal 10, \n and \x0a.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Can someone explain why the decimal value 10, when in Python Struct is showing as \n, and not \x0a?

import struct

marDept5 = struct.pack("b", 10)
print(marDept5)
marDept5a = struct.pack("h", 10)
print(marDept5a)
marDept5b = struct.pack("i", 10)
print(marDept5b)

print("this is decimal 10, struct.pack("b", 10))
print("this is decimal 11, struct.pack("b", 11))
print("this is decimal 12, struct.pack("b", 12))
Output:
b'\n' b'\n\x00' b'\n\x00\x00\x00' this is decimal 10, b'\n' this is decimal 11, b'\x0b' this is decimal 12, b'\x0c'
Why is decimal 10 appearing as \n and not \x0a ? It is after all hex value \x0a. I tried in multiple IDEs and online python compilers and they all return it as value \n. Just looking for an explanation to why?
(Aug-11-2023, 06:39 AM)3python Wrote: [ -> ]Why is decimal 10 appearing as \n and not \x0a ? It is after all hex value \x0a.

Python replaces known ASCII characters with their representation as Escape Sequences.

Documentation: https://docs.python.org/3/reference/lexi...l#literals

These special characters are not all printable. The newline character is only shown in the representation of a str/bytes object. Printing a str -> Newline characters creates a newline. Printing bytes with newline -> Newline Character is not interpreted.

If you need a different representation of binary data, then try binascii.hexlify and binascii.unhexlify. Instead of a str with mixed hexadecimal escape sequences and ascii, you get a hexdecimal string.
Thank you DeaD_EyE! This makes sense now.