Jason M
Jason M

Reputation: 153

Python 3.x - Separating Long Binary String to Short

I had a question about dividing long binary string to shorter ones.

For example, I am trying to convert...

000000100000000011000000100000000010000000100000000001

to...

000000100000000011
000000100000000010
000000100000000001

So basically, I am looking for a python command so that the program can create new line every 18 digits and if possible, introduce a space between first 7 digits and last 11 digits. And then reverse them all back to longer string.

Upvotes: 0

Views: 134

Answers (2)

Blair
Blair

Reputation: 6693

This will divide your long string into shorter strings.

>>> s = '000000100000000011000000100000000010000000100000000001'
>>> print('\n'.join([s[i:i + 7] + ' ' + s[i + 7:i + 18] for i in range(0,len(s),18)]))
0000001 00000000011
0000001 00000000010
0000001 00000000001

This will also put in the spaces you mentioned.

To go in the opposite direction, we can do the following:

>>> f = '0000001 00000000011\n0000001 00000000010\n0000001 00000000001'
>>> print(''.join([c for c in f if c in '01']))
000000100000000011000000100000000010000000100000000001

Upvotes: 5

Dorian Dore
Dorian Dore

Reputation: 962

val = '000000100000000011000000100000000010000000100000000001'
short_val = ''
for i range(len(val) - 1):
    if i % 16 == 0:
       print(short_val)
       short_val = ''
    else:
       short_val += val[i]

Upvotes: 1

Related Questions