python struct pack displaying ascii

2019-08-30 23:25发布

问题:

When using

import struct
struct.pack(">H",31001)

The output is 'y\x19', when I expected '\x79\x19'. I know that \x79 is y in ASCII, but is the information the same? Why is that one byte impacted when the other one is not? I am trying to send a modbus command and am wondering if that is causing a communication issue. I am new to modbus and am having trouble diagnosing why the slave will not respond to the master.

回答1:

You are looking at the result of the repr() function, which the Python interactive interpreter uses on all results that are not None.

Python string contents are shown using ASCII text for any character that is printable, \r, \n and \t for ASCII carriage return, newline and tab characters respectively, and \xhh hex escapes for the rest.

And yes, '\x79' is the exact same byte as 'y':

>>> 'y' == '\x79'
True

but when producing the representation, Python simply prefers to show you the printable ASCII character:

>>> '\x79'
'y'

You could encode the string to 'hex' if you want to see all codepoints represented as hexadecimal:

>>> 'y\x19'.encode('hex')
'7919'


回答2:

Yes, the information is the same. The struct is a sequence of bytes, and printable bytes are displayed as the character they represent. The reason one is shown in escape form and the other isn't is that one is a printable ASCII character and the other isn't.



标签: python struct