Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Python String contains()

Python String Contains

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 ret.

Let’s take a look at some examples now, to illustrate this point.


Using String.__contains__()

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")

Output

String contains target

Since “AskPython” is a substring of the original string, “Hello from AskPython”, the return value is True.

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")

Output

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 True is str1 contains str2, and False otherwise.

>>> print(str.__contains__("Hello from AskPython", "AskPython")
True

Conclusion

In this article, we learned about how we could use the String.__contains__() method to check if a Python string contains another string.


References