Python Forum
Python Struct Question, decimal 10, \n and \x0a. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python Struct Question, decimal 10, \n and \x0a. (/thread-40522.html)



Python Struct Question, decimal 10, \n and \x0a. - 3python - Aug-11-2023

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?


RE: Python Struct Question, decimal 10, \n and \x0a. - DeaD_EyE - Aug-11-2023

(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/lexical_analysis.html#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.


RE: Python Struct Question, decimal 10, \n and \x0a. - 3python - Aug-11-2023

Thank you DeaD_EyE! This makes sense now.