如何在Python中创建一个用零填充的给定长度的字节或bytearray?

问题描述 投票:33回答:2

我找到的所有解决方案都是列表。

谢谢。

python bytearray
2个回答
55
投票

简单:

bytearray(100)

将给你100个零字节。


9
投票

对于bytes,人们也可以使用文字形式b'\0' * 100

# Python 3.6.4 (64-bit), Windows 10
from timeit import timeit
print(timeit(r'b"\0" * 100'))  # 0.04987576772443264
print(timeit('bytes(100)'))  # 0.1353608166305015

Update1:​​使用constant folding in Python 3.7,现在的文字速度快了近20倍。

Update2:显然常量折叠有一个限制:

>>> from dis import dis
>>> dis(r'b"\0" * 4096')
  1           0 LOAD_CONST               0 (b'\x00\x00\x00...')
              2 RETURN_VALUE
>>> dis(r'b"\0" * 4097')
  1           0 LOAD_CONST               0 (b'\x00')
              2 LOAD_CONST               1 (4097)
              4 BINARY_MULTIPLY
              6 RETURN_VALUE
© www.soinside.com 2019 - 2024. All rights reserved.