【问题标题】:different outputs in unpack function in pythonpython中解包函数的不同输出
【发布时间】:2013-07-13 07:04:03
【问题描述】:

当我从控制台接受字符串输入和从变量读取字符串输入时,我在 python 的 unpack 函数中观察到不同的输出。

我从变量中读取字符串输入,输入:

>>> import struct
>>> input="\x0d\x00\x00\x00"
>>> print struct.unpack("I",input)[0]
13

我从控制台读取字符串输入:

>>> import sys
>>> import struct
>>> print struct.unpack("I",sys.stdin.read(4))[0]
\x0d\x00\x00\x00
1680898140

输入字符串相同,但输出不同。它是否以不同的方式解释从控制台读取的输入?如何通过从控制台读取数据获得相同的输入?

【问题讨论】:

  • 问题是,为什么在第二个示例中输入文字 Python 转义码?在您的第一个示例中,您正在创建一个 Python 字符串文字,这意味着 Python 首先要解释转义码..

标签: python unpack


【解决方案1】:

"\x0d\x00\x00\x00"(来自第一个代码)不同于r"\x0d\x00\x00\x00"(== "\\x0x\\x00\x00\x00")来自第二个代码。

>>> struct.unpack("I", '\x0d\x00\x00\x00')[0]
13
>>> struct.unpack("I", r'\x0d\x00\x00\x00'[:4])[0]
1680898140

尝试以下操作:

>>> struct.unpack("I", sys.stdin.readline().decode('string-escape')[:4])[0]
\x0d\x00\x00\x00
13

【讨论】:

    【解决方案2】:

    好像你解压了错误的数据...

    >>> struct.unpack('I','\\x0d')[0]
    1680898140
    

    您对 sys.stdin.read(4) 的调用仅读取 4 个字符:\x0d

    >>> import sys
    >>> import struct
    >>> value = raw_input().decode('string-escape')
    \x0d\x00\x00\x00
    >>> print struct.unpack("I", value)[0]
    13
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2021-04-21
      • 2018-06-24
      • 2021-04-28
      • 2019-03-12
      • 1970-01-01
      相关资源
      最近更新 更多