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? .
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).
with open(infile) as f:
print("".join(line[7::8] for line in f))
Assuming you want each line separately:
with open('tmp.txt', 'r') as f:
for line in f.read().splitlines():
print(line[7::8])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.