-4

I have a binary string and I want to split it into 31 bits array

1101000011010010010000001101101011110010010000001101110011000010110110101100101001000000110100101110011001000000110000101101110011001110110000101110100

That is just an example of a binary string but I need it to work for any binary string keeping the integrity of the binary string if I want to rejoin the array. Once the array is made append 0's to the front making sure the length of everything is 31.

Thanks

Jack
  • 275
  • 1
  • 6
  • 24

1 Answers1

1

You can use regex!

Here

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

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

To pad the item which isn't of len 31 with 0's you can use str.ljust

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

Time for execution:

0.000314

Hope it helps!

Keerthana Prabhakaran
  • 3,766
  • 1
  • 13
  • 23