[SOLVED] Find string in a file and print which line it was found on


How can I find a string in a text file and then print which line that string was found on?

I am using Python 2.7.


In Python, enumerate is handy for this sort of thing:

with open(myfile) as f:
    for index, line in enumerate(f, 1):
        if s in line:
            print("'{0}' found on line {1}".format(s, index))

Answered By – jonrsharpe

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *