How to Check if a String Contains a Substring in Python
In this tutorial, we’ll learn how to program "How to Check if a String Contains a Substring in Python." The objective is to efficiently check whether a string contains a specific substring. This tutorial will guide you through the process step by step to detect if a substring exists within a string. So, let’s get started!
This topic is straightforward to understand. Just follow the instructions I provide, and you’ll complete it with ease. The program I’ll demonstrate will show you the correct and efficient way to check whether a substring exists within a string. So, let’s dive into the coding process!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- def check(string, sub_str):
- if (string.find(sub_str) == -1):
- print("Substring is not present")
- else:
- print("Substring is present")
- while True:
- print("\n============= Check if a String Contains a Substring =============\n")
- string = "I love sourcecodester"
- print(string)
- sub_str = input("Enter a string: ")
- check(string, sub_str)
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- continue
This program checks if a given substring is present within the string "I love sourcecodester" using Python's find() method and repeatedly prompts the user to try again until they decide to exit.
Output:

There you have it we successfully created How to Check if a String Contains a Substring in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language