[英]Printing every Nth (8th character) from a file [Python]
我從文件中轉儲的序列很長。 現在,我想采用此位序列並能夠從中提取每第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位? 。
您可以使用簡單的切片:
with open('thebits.txt', 'r') as f:
for line in f:
print line.strip()[7::8]
您的示例文件提供:
100110
000001
100000
切片[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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.