Python - 生成填充的最有效方法是什么?
问题是:我正在读取相当大的块(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)])
显然,这是非常低效的,因为该减少会进行大量的字符串连接。但我想知道如何用 Python 实现这一点?在 C 中,我只需调用 calloc 即可完成它。
如果使用 Python 无法实现,我愿意将此代码转换为 C 模块和/或在该项目中完全放弃 Python,因为它仍处于早期阶段。
干杯!
编辑:我因为忘记使用 * 运算符而感觉很糟糕。 :-)
这个解决方案对我来说非常有效:
bytes += "\0" * len_diff
编辑 #2:使用 ljust() 稍微简化了我的代码,所以正确的答案是 Jeff。
Here's the problem: I'm reading binary files in fairly large blocks (512 KiB) and wish to pad the last block with zeros whenever it is shorter than the block size.
Currently, I'm doing something like this:
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)])
Obviously this is terribly inefficient since that reduce will make a lot of string concatenations. I'm wondering though, how can I achieve this with Python? In C, I'd simply calloc and be done with it.
If it isn't achievable with Python, I'm willing to convert this code into a C module and/or abandon Python entirely for this project, since it's still on the early stages.
Cheers!
EDIT: I'm feeling terrible for not remembering to use the * operator. :-)
This solution worked perfectly for me:
bytes += "\0" * len_diff
EDIT #2: Using ljust() instead simplified my code a bit, so the correct answer goes to Jeff.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于您使用的是字符串,因此可以使用
ljust()
进行填充。
Since you're working with strings, you can use
ljust()
to do the padding.应该有帮助
should help
试试这个。
或者
try this.
or
怎么样:
How about:
我需要填充一些加密的东西。以下是具体操作方法。
I needed to pad something encrypted. Here's how to do it.