简体   繁体   English

如何读取特定位置字符串,如果它们匹配,然后在 python 中打印所有行?

[英]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.

相关问题 如何使用python读取特定行并在此行中打印特定位置 - how to read a specific line and print a specific position in this line using python 如何按字符比较两个字符串并打印python中的匹配位置 - How to compare two strings by character and print matching positions in python 如何逐行读取文件并仅在python中打印具有特定字符串的行? - How do I read a file line by line and print the line that have specific string only in python? 如何在Python的同一行上打印多行字符串 - How to print multiline strings on the same line in Python 如何获取 python 文件中所有“if”“else”和“elif”位置的行号 - How to fetch line numbers for all 'if' 'else' and 'elif' positions in a python file Python:在两个文件中查找字符串并打印所有行 - Python: Find strings in two file and print all the line Python如何在一行中找到任何或所有字符串列表,然后打印找到的确切字符串 - Python how to find any or all strings-list in a line and then print the exact string found 如何在python列表中查找特定字符串,如果找到则打印位置否则打印0 - How to find a specific string in a python list, if found print the positions else print 0 在python中打印特定行? - Print specific line in python? python读取文件,打印以特定字符串开头的行的一部分 - python read file, print part of line that begins with a specific string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM