Python Program to Check if a Substring Is Present in a Given String

1. Introduction

A substring is a contiguous sequence of characters within a string. Determining if a substring is present in a string involves searching the string for a match to the sequence represented by the substring. Python provides several methods to accomplish this, and we'll explore a straightforward approach.

2. Program Steps

1. Define the main string and the substring to search for.

2. Use a string method to check for the presence of the substring.

3. Print the result of the search.

3. Code Program

# Main string
main_string = "Python programming is fun."

# Substring to search for
substring = "programming"

# Check if the substring is present in the main string using the 'in' keyword
is_present = substring in main_string

# Print the result
print(f"Is the substring '{substring}' present in the string? {is_present}")

Output:

Is the substring 'programming' present in the string? True

Explanation:

1. main_string holds the string to be searched.

2. substring is what we are looking to find within main_string.

3. The in keyword is a Python operator that checks for membership. It returns True if substring is found in main_string and False otherwise.

4. is_present stores the boolean result of the check.

5. The final print statement displays a formatted string indicating whether substring is present in main_string, which is confirmed as True in this case.

Comments