Python does not have a built-in contains method for strings. However, there are a few ways to check if a string contains a substring.
One way is to use the in operator. The in operator returns True if the substring is found in the string, and False if it is not found. For example, the following code checks if the string “hello” contains the substring “ell”:

string = "hello"
substring = "ell"
if substring in string:
    print("The substring is found")
else:
    print("The substring is not found")

This code will print the following output:
The substring is found

Another way to check if a string contains a substring is to use the index() method. The index() method returns the index of the first occurrence of the substring in the string. If the substring is not found, the index() method will raise a ValueError exception. For example, the following code checks if the string “hello” contains the substring “ell”:

string = "hello"
substring = "ell"
index = string.index(substring)
if index != -1:
    print("The substring is found at index", index)
else:
    print("The substring is not found")

This code will also print the following output:
The substring is found at index 2
Finally, you can also use the re module to check if a string contains a substring. The re module provides a number of functions for working with regular expressions. For example, the following code checks if the string “hello” contains the substring “ell” using a regular expression:

import re
string = "hello"
substring = "ell"
pattern = r"ell"
if re.search(pattern, string):
    print("The substring is found")
else:
    print("The substring is not found")

This code will also print the following output:
The substring is found

In conclusion

There are a few ways to check if a string contains a substring in Python. The best method to use will depend on your specific needs.

Support On Demand!

                                         
Python