Search for a String in Text Files using enumerate()

We are just finding string is present in the file or not using the enumerate() in Python.

Python3




with open(r"myfile.txt", 'r') as f:
    for index, line in enumerate(f):
         
        # search string
        if 'Line 3y' in line:
            print('string found in a file')           
            # don't look for next lines
            break
         
    print('string does not exist in a file')


Output:

string does not exist in a file


Python – How to search for a string in text files?

In this article, we are going to see how to search for a string in text files using Python

Example:

string = “GEEK FOR GEEKS”
Input: “FOR” 
Output: Yes, FOR is present in the given string.

Text File for demonstration:

myfile.txt

Similar Reads

Finding the index of the string in the text file using readline()

In this method, we are using the readline() function, and checking with the find() function, this method returns -1 if the value is not found and if found it returns 0....

Finding string in a text file using read()

...

Search for a String in Text Files using enumerate()

we are going to search string line by line if the string is found then we will print that string and line number using the read() function....

Contact Us