[英]How read specific positions strings and if they match, then print all the line in python?
I'm learning python.我正在学习蟒蛇。 I want to do this:我想做这个:
I have a text file with a lot of lines like this (each line have 26 strings, some strings can be whitespaces or not, followed the number of line):我有一个文本文件,有很多这样的行(每行有 26 个字符串,有些字符串可以是空格,也可以不是空格,后面是行数):
BBBTHTHTTTTCCCHHHHHH 1
CCCTTTTHHHHHHHHHHHTTTTTTTT 2
TTTTTTTTTTHHHHHHHHCCCCCC 3
CTCTTTTTTTTTTTTTTHHHHHHHHH 4
I want to read the string from 22 to 26 position, and if all these positions are H, then print the complete line.我想从 22 到 26 位置读取字符串,如果所有这些位置都是 H,则打印完整行。 For example:例如:
BBBTHTHTTTTCCCHHHHHH 1
CTCTTTTTTTTTTTTTTHHHHHHHHH 4
My script is this我的脚本是这样的
f = open("file.txt", "r")
lines = [line for line in f.readlines() if line[22:26]=="H"]
print lines
anybody can help me to fix it?有人可以帮我解决吗? Thanks for your support and tips.感谢您的支持和提示。
Try this:尝试这个:
with open('file.txt') as f:
for i in f:
if i[21:26]=='HHHHH':
print(i)
You can use split()
and endswith()
您可以使用split()
和endswith()
res = [line for line in f if line.split()[0].endswith('H' * (26 - 21))]
print(res)
Output:输出:
[' BBBTHTHTTTTCCCHHHHHH 1', 'CTCTTTTTTTTTTTTTTHHHHHHHHH 4']
It can be :有可能 :
with open('file.txt') as f:
lines = '\n'.join([l for l in f.read().splitlines() if l[22:26] == 'HHHH'])
print(lines)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.