Python String Contains Tutorial Example | Python String __contains__()
Python String Contains Tutorial Example | Python String __contains__() is today’s topic. Methods that start with underscores are considered private methods in Python. Some developers do not use these private methods in their code. They said that avoid using these private methods on production code. Now back to the Python String Contains method. Python String class has the __contains__() method that we can use to check if it contains another string or not.
Python String Contains Tutorial Example
Python string __contains__() is the instance method and returns the boolean value True or False depending on whether the string contains the specified string or not. Note that the Python string __contains__() function is case sensitive. It returns false in the scenario like a character instead of A character.
See the below syntax of Python __contains__() method.
Let’s look at the below example for python string __contains__() method.
# app.py data = 'AppDividend' print(data.__contains__('Div'))
Now, let’s see the output.
In the above code, substring Div is inside the data string. That is why it returns True.
See the below more examples.
Now, __contains__() function is a case sensitive. So, if you put the character app instead of App in the above program, then it will return false. See the below code.
# app.py data = 'AppDividend' print('AppDividend contains app =', data.__contains__('app'))
See the below output.
Python String Contains method checks the substring, which includes in the string. If it includes then return True otherwise False.
Let’s look at the second example in which we will ask a user to enter both the input strings and check if the first string contains the second string or not.
# app.py strA = input('Please enter first input string\n') strB = input('Please enter second input string\n') print('First Input String Contains Second String? ', strA.__contains__(strB))
See the following output.
If you also need the first index of the substring, you can use find(substr) to find the index. If Python String find() method returns -1, it means that substring doesn’t exist in the string.
Python String index() method returns the index of a substring inside the string if found.
So, you can use the above two methods instead of Python String __contains__() method to check the substring inside the string.
Finally, Python String Contains Tutorial Example | Python String __contains__() article is over.