Slice a binary number into groups of five digits

后端 未结 7 1265
野性不改
野性不改 2021-01-21 07:34

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

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

相关标签:
7条回答
  • 2021-01-21 07:55

    How about using a regular expression?

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

    This will break though if your input string contains newlines, that you want in the grouping.

    0 讨论(0)
  • 2021-01-21 08:07
    >>> 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 讨论(0)
  • 2021-01-21 08:09
    >>> a='00010100011011101101110100010111'
    >>> [a[i:i+5] for i in range(0, len(a), 5)]
    ['00010', '10001', '10111', '01101', '11010', '00101', '11']
    
    0 讨论(0)
  • 2021-01-21 08:15
    >>> [''.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 Hewgill, what to do with the two trailing bits? Here are some 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']
    
    0 讨论(0)
  • 2021-01-21 08:15

    Another way to group iterables, from the 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 讨论(0)
  • 2021-01-21 08:19

    Per your comments, you actually want base 32 strings.

    >>> import base64
    >>> base64.b32encode("good stuff")
    'M5XW6ZBAON2HKZTG'
    
    0 讨论(0)
提交回复
热议问题