Python Tutorial (33) - Example: Determine if a substring exists in a string

Time: Column:Python views:270

Check if a Substring Exists in a Given String

In this section, we will define a string and check whether a specified substring exists within the string.

Example

def check(string, sub_str): 
    if (string.find(sub_str) == -1): 
        print("Not found!") 
    else: 
        print("Found!")

Code Example:

string = "www.runoob.com"
sub_str = "runoob"
check(string, sub_str)

Output:

Found!

In this example, the find() method is used to check if the substring is present in the given string. If the method returns -1, it indicates that the substring is not found, otherwise, it exists.