Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get an index value based on a string available on that index?

For a given text file (sample.txt), I would like to get index value based on a string that is present on that line (index).

An example file contains following text (sample.txt):

line 1: open a file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

line 2: Read a file and store it in a variable.

line 3: check condition using ‘in’ operator for string present in the file or not.

line 4: If the condition true print the index in which the string is found.

line 5: Close a file.

if my target string is ‘variable’. The output I would like to have is:
2

>Solution :

This should do:

def indicesOfQueryOnFile(query, file):
    with open(file, 'r') as f:
        cleanLines = [line for line in f.readlines() if len(line.strip()) > 0]
        indices = [i + 1 for i, line in enumerate(cleanLines) if query in line]
    
    return indices

For the text file:

line 1: open a file.

line 2: Read a file and store it in a variable.

line 3: check condition using ‘in’ operator for string present in the file or not.

line 4: If the condition true print the index in which the string is found.

line 5: Close a file.

another line with variable

It would output:

indicesOfQueryOnFile('variable', 'test.txt')
# [2, 6]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading