显示ascii的python结构包 [英] python struct pack displaying ascii
问题描述
使用时
导入结构struct.pack(">H",31001)
输出是 'y\x19'
,当我期望 '\x79\x19'
时.我知道 \x79 在 ASCII 中是 y,但是信息是一样的吗?为什么一个字节会受到影响,而另一个则没有?我正在尝试发送一个 modbus 命令并且想知道这是否会导致通信问题.我是 modbus 的新手,无法诊断为什么从站不响应主站.
您正在查看 repr()
函数的结果,Python 交互式解释器将其用于所有非 repr()
函数的结果代码>无代码>.
Python 字符串内容使用 ASCII text 表示任何可打印的字符,\r
、\n
和 \t
分别用于 ASCII 回车、换行符和制表符,\xhh
用于其余的十六进制转义.
是的,'\x79'
与 'y'
的字节完全相同:
但是在生成表示时,Python 只是更喜欢向您显示可打印的 ASCII 字符:
<预><代码>>>>'\x79''你'如果您想查看以十六进制表示的所有代码点,您可以将字符串编码为'hex'
:
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.
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'
这篇关于显示ascii的python结构包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!