Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing a string into a list of smaller strings of certain length

If i have this string:

"0110100001100101011011000110110001101111"

How can I divide it at every eighth character into smaller strings, and put it into a list, so that it looks like this?:

['01101000','01100101','01101100','01101100','01101111']

So far, I can't figure out how this would be possible.

I should mention, since my strings are in binary so the length is always a multiple of 8.

like image 495
Peaser Avatar asked Dec 08 '22 07:12

Peaser


2 Answers

>>> mystr = "0110100001100101011011000110110001101111"
>>> [mystr[i:i+8] for i in range(0, len(mystr), 8)]
['01101000', '01100101', '01101100', '01101100', '01101111']

The solution uses a so called list comprehension (this seems to be a pretty decent tutorial) and is doing basically the same as Aleph's answer, just in one line.

like image 178
timgeb Avatar answered Dec 11 '22 08:12

timgeb


t=[]
for i in range(len(yourstring)/8):
    t.append(yourstring[i*8: (i+1)*8])
like image 36
Aleph Avatar answered Dec 11 '22 09:12

Aleph