简体   繁体   English

从文件打印第N个字符(第8个字符)[Python]

[英]Printing every Nth (8th character) from a file [Python]

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. 现在,我想采用此位序列并能够从中提取每第8位。 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? 如何从每行中提取每8位? .

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). 切片[7::8]从第8个字符开始为您提供第8个字符(从0开始索引7)。

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM