How to Search for a Substring in a String in Python

In this tutorial, we will learn how to program "How to Search for a Substring in a String in Python." The objective is to determine whether a substring exists within a given string. This tutorial will guide you step by step through the process of checking for a substring. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.

This topic is straightforward to understand. Simply follow the instructions provided, and you will be able to complete it with ease. The program will guide you step by step through the process of searching for a substring 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.
  1. while True:
  2.     print("\n============= Search for a Substring in a String =============\n")
  3.  
  4.     string = input("Enter a string: ")
  5.     sub_str = input("Enter the substring to search: ")
  6.  
  7.     if string.find(sub_str) == -1:
  8.         print("Substring not found in string! ❌")
  9.     else:
  10.         print("Substring found in string! ✅")
  11.  
  12.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  13.     if opt == 'no':
  14.         print("Exiting program...")
  15.         break
  16.     elif opt != 'yes':
  17.         print("Invalid choice. Exiting program...")
  18.         break

This program searches for a substring within a given string. It takes user input for both the main string and the substring, then uses the `find()` method to check if the substring exists. If found, it prints a success message; otherwise, it indicates the substring was not found. The loop continues until the user chooses to exit.

Output:

There you have it we successfully created How to Search for a Substring in a String 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

Python Tutorials