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 =

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

Using try and except

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

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

6 thoughts on “Check if a string is in a text file using Python 3

  1. Can I just say what a relief to discover somebody who actually understands what they are
    discussing online. You definitely understand how to bring an issue to light and make it important.
    More and more people have to read this and understand this side of your story.

    I was surprised that you are not more popular because you certainly have the gift.

    Liked by 1 person

  2. Do you mind if I quote a few of your articles as long as I provide credit and sources back to your webpage?
    My blog is in the very same area of interest as yours and my visitors would certainly benefit from
    some of the information you present here. Please let me know if this okay with you.


  3. I’ve learn a few just right stuff here. Certainly price bookmarking for
    revisiting. I wonder how a lot attempt you put to create this sort of
    fantastic informative site.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s