我从文件中转储了很长的位序列。现在,我想采用这个位序列,并能够从中提取每个第8位。例如:
100010010101000001001110010001110000110100001010
000110100000101000000000000000000000000000001101
010010010100100001000100010100100000000000000000
etc
会给:
100110
(extraction from second line)
(extraction from third line)
etc
到目前为止,我有以下代码:
#/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}
如何从每一行中提取每个第8位?
答案 0 :(得分:5)
您可以使用简单的切片:
with open('thebits.txt', 'r') as f:
for line in f:
print line.strip()[7::8]
您的示例文件提供:
100110
000001
100000
切片[7::8]
为您提供从第8个开始的每个第8个字符(7个从0开始索引)。
答案 1 :(得分:2)
with open(infile) as f:
print("".join(line[7::8] for line in f))
答案 2 :(得分:0)
假设你想要分开每一行:
with open('tmp.txt', 'r') as f:
for line in f.read().splitlines():
print(line[7::8])