How to Check if Substring Exists in Given String in Python


Here this example will teach us how to check whether a substring exists in a given string.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

str = input("Please input the string: ")
subStr = input("Please input the substring to be checked: ")
if str.find(subStr) == -1:
    print("The substring does not exist.")
else:
    print("The substring does exist.")

Output:

Case 1:
Please input the string: Hello Python
Please input the substring to be checked: Python
The substring does exist.

Case 2:
Please input the string: Hello Python
Please input the substring to be checked: cat
The substring does not exist.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments