如何在Python中创建给定长度的字节或字节数组,并用零填充?

2024-04-19 07:48:37 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

对于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倍。

更新2: 显然,固定折叠有一个限制:

>>> 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

简单:

bytearray(100)

会给你100个零字节。

相关问题 更多 >