In this article, we’ll take a look at finding whether one Python string contains another string.
How can we easily do it? Python has a built-in string method String.__contains__(), which we can use easily.
Let’s look at how we can use this method.
Syntax of String.__contains__()
This function will take two strings, and return if one string belongs to another. The return type of this method is therefore a boolean, so it will return either a True, or a False.
As to how we can call this method, we use it on a string object, to check if another string is within this string object.
ret = str_object.contains(another_string)
This will check if
str_object contains the string
another_string, with the return value being stored to
Let’s take a look at some examples now, to illustrate this point.
We’ll check if a Python string contains another string.
my_str = "Hello from AskPython" target = "AskPython" if (my_str.__contains__(target)): print("String contains target!") else: print("String does not contain target")
String contains target
Since “AskPython” is a substring of the original string, “Hello from AskPython”, the return value is
This method is case sensitive, so the string “askpython” will not get matched.
my_str = "Hello from AskPython" target = "askpython" if (my_str.__contains__(target)): print("String contains target!") else: print("String does not contain target")
String does not contain target
Using Python String contains() as a Class method
We can also use this as a class method on the
str class, and use two arguments instead of one.
ret = str.__contains__(str1, str2)
This is similar to our previous usage, but we invoke this as a Class method on the String class. This will return
>>> print(str.__contains__("Hello from AskPython", "AskPython") True
In this article, we learned about how we could use the String.__contains__() method to check if a Python string contains another string.
- JournalDev article on Python String contains() method