. Advertisement .
. Advertisement .
In Python, there are several methods you can use to check whether or not a substring is in the main string. One of them is the Python __contains__ function. Don’t know what this method is and how it works? Do not worry; our guide will cover everything you need to know about this useful command.
What is Python __contains__?
The Python String class has a function called
__contains__. This method can determine whether or not a provided substring is a part of a string. This instance function is utilized to give back boolean values, such as False or True.
Suppose your string is found in another string; you will receive the value True. If not, the returned value is False. Keep in mind that Python has case-sensitive character encoding.
__contains__ is a dunder (or magical) method, which is preceded by two underscores and followed by another two underscores (dunder is short for double underscore). This type of method is not intended to be invoked explicitly but instead invoked as a part of other built-in operations.
The operator in is connected to the method
__contains__ in this situation. In Python, this operator determines if a given value is a component member of a sequence, such as an array, string, tuple, or list. Suppose the element is present; it will return a value True. If not, then a value False will be returned.
How Python __contains__ Works
__contains__ specifies the instances’ behavior on the operator in’s right side. Meanwhile, the operator in determines if a provided value is included in the sequence.
Check out the following example.
str1 = "ITtutoria" str2 = "IT" val = str1.__contains__(str2) print(val)
__contains__ was used in the example above to determine if a provided substring was contained in the string.
Dunder methods are called within a class. You can utilize the class’s method
__contains__ to call it and perform an action. It can also be overloaded to return a different result when linked to a class.
Here is a sample for you to use as a reference.
class pyContains(object): name = 'ITtutoria' def __contains__(self, m): if self.name: return False b = pyContains() print('tutoria' in b)
As you can see, we made the method
__contains__ give back the value False in case a substring is present in the string. Because it is called when the operator in is utilized, the ultimate result comes out as False even though there is a stack string.
The Bottom Line
So there you have all the information about the Python __contains__ function, from the definition to how it operates. Hopefully, this guide cleared out all your confusion on this subject.If you desire to gain more Python skills, such as how to change seaborn plot size or truncate a float, our detailed guides will help you. Check those out now!
Leave a comment