【问题标题】:Strip \x00 and \x02 from string从字符串中去除 \x00 和 \x02
【发布时间】:2019-12-12 21:38:24
【问题描述】:

我正在读取二进制文件以获取其中包含的信息。我的目标是从文件中的特定位置和可变长度提取一些字符。 我阅读文件如下:

with open("raw_files/P1925aM", "rb") as binary_file:

binary_file.seek(436, 0)

some_information = binary_file.read(331)

some_information = some_information.decode('ascii').rstrip('\x00')

binary_file.close()

输出是一个变量(类“字节”),它包含以下内容:

“17627005 SWU1.1\x00\x00\x00....”

到目前为止,我设法将字节变量解码为 ASCII 并使用以下方法去除 '\x00:

some_information = some_information.decode('ascii').rstrip('\x00')

输出如下:17627005 SWU1.1 这正是我想要的。

现在我有一个变量(类'str')。 如果变量看起来像这样,我现在遇到的问题是:

“17627005 SWU1.1\x02\x00\x00....”

some_information = some_information.decode('ascii').rstrip('\x02')

不起作用。输出保持“17627005 SWU1.1 \x02\x00\x00....”

任何提示我在这里做错了什么?

【问题讨论】:

  • 您将其标记为 python-2.7,但您在代码中将 bytes 作为类引用。 bytes 只是 Python 2.7 上 str 的别名。你确定你没有使用 Python 3?
  • 你是对的。我正在使用 Python 3.6。这是一个错误。

标签: python python-3.x strip


【解决方案1】:

strip 系列函数只从字符串的 end 中删除;您的 \x02 不是字符串中的最后一个字符。如果您想从字符串的右侧删除\x00\x02 的任意组合,请将两者都传递给rstrip

some_information = some_information.decode('ascii').rstrip('\x00\x02')

【讨论】:

    【解决方案2】:

    您可以使用正则表达式匹配可打印字符:

    import re
    ...
    rawdata = some_information.decode('ascii')
    result = re.match(r"[\x20-\x7E]+", rawdata).group()
    

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 2013-09-23
      • 1970-01-01
      • 2013-01-17
      相关资源
      最近更新 更多