Python Example | Python __contains__ Method Explained

This python example code will show us how to use python __contains__ method corrrectly.

Python __ contains __ is a method of the String class in Python. It can check whether a given substring is part of a string or not.

str1 = "notehope.com"
str2 = "note"

val = str1.__contains__(str2)
print(val)

Run this code, we will get:

True

We also can overwrite it.

class abc(object):

    name = 'notehope.com'

    def __contains__(self, m):
        if self.name: 
            return False

b = abc()
print('stack' in b)

We will get:

False