# Define a string my_string = "Hello, world!" # Check if the string contains the substring "world" if "world" in my_string: print("The string contains the substring.") else: print("The string does not contain the substring.")
Alternatively, you can use the find() method to check if a string contains a substring. This method returns the index of the first occurrence of the substring, or -1 if the substring is not found. Here's an example:
# Define a string my_string = "Hello, world!" # Find the index of the substring "world" index = my_string.find("world") # Check if the substring was found if index != -1: print("The string contains the substring.") else: print("The string does not contain the substring.")
This will also print 'The string contains the substring'.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.