python struct pack displaying ascii

你说的曾经没有我的故事 提交于 2019-12-25 03:35:23

问题


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.



来源:https://stackoverflow.com/questions/26264261/python-struct-pack-displaying-ascii

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!