从文件中每隔n(8个字符)打印一次[Python]

2024-09-30 16:31:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个文件中转储了一长串的位。现在,我想取这个位序列,并能从中提取每8位。例如:

100010010101000001001110010001110000110100001010
000110100000101000000000000000000000000000001101
010010010100100001000100010100100000000000000000
etc

会给出:

^{pr2}$

到目前为止,我有以下代码:

 #/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位? . 在


Tags: 文件代码txtbinusraswithetc
3条回答

可以使用简单切片:

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

示例文件给出了:

^{pr2}$

[7::8]提供从第8个开始的每8个字符(从0索引的7个)。在

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

假设您希望每一行分开:

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

相关问题 更多 >