Javatpoint Logo
Javatpoint Logo

Contains in Python

The __contains__() method is a method of the Python String class that can be used to check whether the class contains another string or not. Moreover, the methods that begin with underscores are said to be the private methods in Python, so is the __contains__() method. However, there are some developers that avoid the use of these private methods in their code.

But for now, let us explore some fundamentals of the __contains__() method in Python String.

Python String contains

The __contains__() method in Python String is an instance method that returns the Boolean value as True or False, relying on the condition if the string object has the particular string object or not.

Note: The __contains__() method in Python String is case sensitive.

Here are some basic examples for the Python String __contains__() method:

Example 1:

Output:

my string contains 'w' = True
my string contains 'W' = False
my string contains 'a' = False
my string contains 'c' = True
my string contains 'E' = True

Explanation:

In the above program, we have created a string as my_string. We have then used the Python string __contains__() method to check whether the given string object is in the string or not. For instance, we have checked if 'w' is present in the 'welcome' string, and as a result, it returns True. Similarly, the output comes out to be False for 'W', 'a', and 'E', respectively.

Apart from the above example, the __contains__() method also functions like the str class method.

Let us consider the following example to understand its behavior:

Example:

Output:

True
False

Explanation:

In the above example, we have used the __contains__() method like the str class method and check whether the given string object is present in the string or not.

Let us understand another example in which we will be asking the users to input both the strings and check whether the second string is a part of the first string.

Example:

Output:

Please input the first input string:
Hey there! This is my Computer.
Please input the second input string:
Comp
Checking if the second string is a part of first string?: True

Explanation:

In the above example, we have asked the user to enter two different strings using the input() method. And at last, we have used the __contains__() method to check if the second string is a part of the first string or not. As a result, the user provided the inputs to the program, and the program executed the function to check for the result.






Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA