【问题标题】:Python - What is the most efficient way to generate padding?Python - 生成填充的最有效方法是什么?
【发布时间】:2011-08-12 00:43:24
【问题描述】:

问题是:我正在读取相当大的块 (512 KiB) 中的二进制文件,并希望在最后一个块小于块大小时用零填充。

目前,我正在做这样的事情:

bytes = f.read(self.chunksize)
if len(bytes) > 0:
    len_diff = self.chunksize - len(bytes)
    if len_diff > 0:
        bytes += reduce(lambda x,y: x+y, ["\0" for i in range(0, len_diff)])

显然这是非常低效的,因为 reduce 会产生大量的字符串连接。不过我想知道,我怎样才能用 Python 实现这一点?在 C 语言中,我只需 calloc 就可以了。

如果使用 Python 无法实现,我愿意将此代码转换为 C 模块和/或完全放弃 Python 用于该项目,因为它仍处于早期阶段。

干杯!

编辑:不记得使用 * 运算符我感觉很糟糕。 :-)

这个解决方案非常适合我:

bytes += "\0" * len_diff

编辑#2:使用 ljust() 反而简化了我的代码,所以正确答案归 Jeff 提供。

【问题讨论】:

标签: python padding


【解决方案1】:

由于我们在这里处理字符串对象,您不能只使用ljust() 进行填充吗?

bytes = f.read(self.chunksize)
if bytes:
    bytes = bytes.ljust(self.chunksize, '\0')

【讨论】:

  • 太棒了!正是我想要的。这些天我没有做太多的字符串操作。 :P
  • 在 Python 3 中,ljust 的第二个参数必须是b'\0'
【解决方案2】:
bytes += "\0"*len_diff 

应该有帮助

【讨论】:

  • 我什至因为没有先考虑这一点而感到难过。 :) 只要允许我就会接受。
  • 抱歉,为@Jeff 提供的解决方案实际上是我正在寻找的,更不用说骇人听闻了。不过,这个也可以。 :)
【解决方案3】:

试试这个。

bytes = "\0" * self.chunksize
rbytes = f.read(self.chunksize)
bytes[:len(rbytes)] = rbytes

bytes = f.read(self.chunksize)
bytes += "\0" * (self.chunksize - len(bytes))

【讨论】:

    【解决方案4】:

    怎么样:

    bytes += "\0"*len_diff
    

    【讨论】:

      【解决方案5】:

      我需要填充一些加密的东西。以下是操作方法。

      from Crypto.Util.Padding import pad
      
      ...
      _bytes = pad(_bytes, block_size)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-30
        • 1970-01-01
        • 1970-01-01
        • 2012-01-21
        • 2012-11-10
        • 1970-01-01
        • 2021-07-27
        • 2010-11-20
        相关资源
        最近更新 更多