Cut a binary number into groups of five digits

Is there any neat trick to chop a binary number into groups of five digits in python?

'00010100011011101101110100010111' => ['00010', '00110', '10111', ...]

Edit: I want to write a cipher / encoder to create "easy to read by phone" tokens. Base32 standard encoding has the following disadvantages:

  • The potential for generating random words f *
  • Uses confused characters, such as the characters "I", "L", "O" (can be confused with 0 and 1)
  • Easy to guess sequences ("AAAA", "AAAB", ...)

I was able to knock over myself in 20 lines of python, thanks to everyone. My encoder leaves "I", "L", "O" and "U", and the resulting sequences are hard to guess.

+3
source share
7 answers
>>> a='00010100011011101101110100010111'
>>> [a[i:i+5] for i in range(0, len(a), 5)]
['00010', '10001', '10111', '01101', '11010', '00101', '11']
+6
source
>>> [''.join(each) for each in zip(*[iter(s)]*5)]
['00010', '10001', '10111', '01101', '11010', '00101']

or

>>> map(''.join, zip(*[iter(s)]*5))
['00010', '10001', '10111', '01101', '11010', '00101']

[EDIT]

The question was raised by Greg Hugill, what to do with two tails? Here are a few possibilities:

>>> from itertools import izip_longest
>>>
>>> map(''.join, izip_longest(*[iter(s)]*5, fillvalue=''))
['00010', '10001', '10111', '01101', '11010', '00101', '11']
>>>
>>> map(''.join, izip_longest(*[iter(s)]*5, fillvalue=' '))
['00010', '10001', '10111', '01101', '11010', '00101', '11   ']
>>>
>>> map(''.join, izip_longest(*[iter(s)]*5, fillvalue='0'))
['00010', '10001', '10111', '01101', '11010', '00101', '11000']
+6
source

32.

>>> import base64
>>> base64.b32encode("good stuff")
'M5XW6ZBAON2HKZTG'
+1

?

>>> import re
>>> re.findall('.{1,5}', '00010100011011101101110100010111')
['00010', '10001', '10111', '01101', '11010', '00101', '11']

, , .

+1

, .

, Generators

from itertools import islice
def slice_generator(an_iter, num):
    an_iter = iter(an_iter)
    while True:
        result = tuple(islice(an_iter, num))
        if not result:
           return
        yield result

, :

>>> l = '00010100011011101101110100010111'
>>> [''.join(x) for x in slice_generator(l,5)]
['00010', '10001', '10111', '01101', '11010', '00101', '11']
+1
source
>>> l = '00010100011011101101110100010111'
>>> def splitSize(s, size):
...     return [''.join(x) for x in zip(*[list(s[t::size]) for t in range(size)])]
...  
>>> splitSize(l, 5)
['00010', '10001', '10111', '01101', '11010', '00101']
>>> 
0
source

Another way to group iterations from itertools examples :

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
0
source

Source: https://habr.com/ru/post/1771585/


All Articles