Check if a string is in a text file using Python 3

Check whether the string given by the user belongs to the text file or not using Python 3. A user has to give an input of a string. The script will check whether the string is there in the text file or not.

My objectives are

  1. Printing “Matched” if the input string is there in the text file.
  2. When user gives no input it tells user to “Enter a string” until gets any value.
  3. If the string is not there in the text file, it tells user to give an input again until the result is “Matched”.

I have written the script in two different ways.

  • if-else
  • try and except

I was stuck at completing my 3rd objective using if-else method. The “continue” statement in the else part was not working as the way I wanted. SanketDG from dgplug has helped me to achieve what I wanted , so thanks to him 🙂

Using If-else


#!/usr/bin/env python3

#Open the file
fobj = open("example.txt")
text = fobj.read().strip().split()

#Conditions
while True:
    s = input("Enter a string: ") #Takes input of a string from user
    if s == "": #if no value is entered for the string
        continue
    if s in text: #string in present in the text file
        print("Matched")
        break
    else: #string is absent in the text file
        print("No such string found,try again")
        continue
fobj.close()

Using try and except


#!/usr/bin/env python3
with open("example.txt") as fobj:
    text = fobj.read().strip().split()
    while True:
        try:
            s = input("Enter a string: ")
            if s == "":
                continue
            if s in text:
                print("Matched")
                break
            raise Exception("No such string found, try again")
        except Exception as e:
            print(e)

Modifications of the scripts are always welcome. Please leave comments for any kind of modification 🙂

Advertisements