0

I have a long sequence of bits that I dumped from a file. Now, I want to take this sequence of bits and be able to extract every 8th bit from it. For example:

100010010101000001001110010001110000110100001010
000110100000101000000000000000000000000000001101
010010010100100001000100010100100000000000000000
etc

would give:

100110
(extraction from second line)
(extraction from third line)
etc

I have the following code so far:

 #/usr/bin/python

 with open("thebits.txt", 'r') as f:
        content = [x.strip('\n') for x in f.readlines()]
        {//logic to extract every 8th bit from each line and print it}

How can I extract every 8th bit from each line? .

3 Answers 3

5

You can use simple slicing:

with open('thebits.txt', 'r') as f:
    for line in f:
        print line.strip()[7::8]

Your example file gives:

100110
000001
100000

The slice [7::8] gives you every 8th character starting from the 8th (7 indexed from 0).

2
with open(infile) as f:
    print("".join(line[7::8] for line in f))
0
0

Assuming you want each line separately:

with open('tmp.txt', 'r') as f:
    for line in f.read().splitlines():
        print(line[7::8])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.