简体   繁体   中英

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

      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. 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()

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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