# 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'.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.