关于python:将二进制字符串拆分为31位字符串

Split binary string into 31bit strings

本问题已经有最佳答案,请猛点这里访问。

我有一个二进制字符串,我想把它分成31位数组

110100001101100101000011011011011011010010101111001001000001101110011000011011010110010101000011011011011011100110011001000001100001011100111011000101110100

这只是一个二进制字符串的例子,但是如果我想重新加入数组,我需要它为任何保持二进制字符串完整性的二进制字符串工作。一旦创建了数组,在前面附加0,确保所有内容的长度都是31。

谢谢


你可以使用regex!

在这里

{n,m} Matches at least n and at most m occurrences of the preceding expression.

1
2
3
4
>>> import re
>>> s = '1101000011010010010000001101101011110010010000001101110011000010110110101100101001000000110100101110011001000000110000101101110011001110110000101110100'
>>> re.findall(r'.{,30}''.',s)
['1101000011010010010000001101101', '0111100100100000011011100110000', '1011011010110010100100000011010', '0101110011001000000110000101101', '110011001110110000101110100']

要用0填充不属于len 31的项目,可以使用str.ljust

1
2
>>> [i.ljust(31,'0') for i in re.findall(r'.{,30}''.',s)]
['1101000011010010010000001101101', '0111100100100000011011100110000', '1011011010110010100100000011010', '0101110011001000000110000101101', '1100110011101100001011101000000']

执行时间:

1
0.000314

希望它有帮助!