Python:需要帮助拆分二进制代码的输入,没有空格

3 python binary python-2.7

需要拆分每8个字符,这样它就会成为一个列表,然后我可以转换成ascii然后翻译成英文.我只是不知道如何将输入(一个大的二进制数字串)分成可读的二进制数,而不是只有一个字符串.

例如,输入字符串"010000010100001001000011"可以按如下方式拆分为八位字节:"01000001","01000010","01000011".

到目前为止我有什么:

def main():
    import string

    #take user input of binary
    code = raw_input ('Please type in your binary code to be decoded: ')

    #split the code
    for word in code:
         print code[0::8] + ' '

    #replace the input with the variables
    ascii = ' '
    for word in code:
        ascii = ascii + int(word,2)

    english = ' '
    for word in acsii:
        english = english + chr(word)

    #print the variables to the user
    print english

#call Main
main()
Run Code Online (Sandbox Code Playgroud)

wim*_*wim 5

通过列表推导,这应该可以帮到你一些方法:

>>> b = '010000010100001001000011'
>>> bin_chunks = [b[8*i:8*(i+1)] for i in xrange(len(b)//8)]
>>> print bin_chunks
['01000001', '01000010', '01000011']
>>> ints = [int(x, 2) for x in bin_chunks]
>>> print ints
[65, 66, 67]
>>> chars = [chr(x) for x in ints]
>>> print chars
['A', 'B', 'C']
>>> print ''.join(chars)
ABC
Run Code Online (Sandbox Code Playgroud)