EDUCBA

EDUCBA

MENUMENU
  • Blog
  • Free Courses
  • All Courses
  • All in One Bundle
  • Login
Home Software Development Software Development Tutorials Python String Tutorial Python String Contains

Python String Contains

Updated April 11, 2023

Python String Contains

Introduction to Python String Contains

In this article, we will see the string method for checking if the given substring is present in the given string and return true if it is present else it returns false such string method is known as _contains_() method of String class in Python. In Python, pandas also provide series.str.contains the () function to check if the pattern given is contained in the given string of series and this function also returns a Boolean value such as true if the pattern is present in the string of series and false if not present. There are other different ways also for checking if the string is present or not in the given another string in Python such as using a regular expression, “in” operator, find(), etc.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Working of string _contains_() Function in Python

In this article, we will see the string class provides _contains_() method for testing if there is a presence of a given substring in the string. In Python, there is another module named “operator” which also provides contains() function and this function also works similarly to the _contains_() function of string class. There is also another option to find the string of series using pandas which will also provide function series.str.contains() to check for the presence of a given pattern in the string of series.

Now let us demonstrate the above functions with examples:

Python has built-in string function for finding substring in the given string using String._contains_() function.

Syntax:

str._contains_(substring)

So this function _contains_() takes two strings. In the above syntax, we can see “str” is a string object which has one string and “substring” has another string. So, in general, the working of this function is it will check if the string object “str” in the syntax contains a string (substring) specified or passed as an argument to the _contains_() function. We should note that this function is case-sensitive.

Example of Python String Contains

Below are the different examples of Python String Contains:

Example #1

Code:

print("Python program to demonstrate _contains_() function")
print("\n")
str1 = "Educba Training"
sub_str = "Educba"
if (str1.__contains__(sub_str)):
    print("The given String contains the given substring")
    print(sub_str)
    print("\n")
else:
    print("The given String does not contain substring")

Output:

Python String Contains 1

In the above program, we can see that we have declared a string “str1” as “Educba Training” and “sub_str” as “Educba”. Then using the “if” statement we will check for the presence of a substring in the given string using _contains_() function which results in true value and therefore it prints the substring and if it is not present then it will return false.

The above string function _contains_() can be made as a class method also and this can be done by using two parameters to the method of the String class str.

Syntax:

o = str_cl._contains_(s1, s2)

So this function is invoked as a class method on string class and this function will return true if s1 string contains s2 string else it returns false.

Code:

print(str.__contains__("Educba Training Institute", "Institute"))

Output:

True

Now we will see how “operator” module of Python provides contains() function which also works similarly to the string function _contains_() and let us demonstrate it in the below example.

Example #2

Code:

import operator
print("Python program to demonstrate contains() function of operator module ")
print("\n")
str1 = "Educba is best in programming courses."
if operator.contains(str1, "best"):
    print ("The given substring is present in the string.")
else :
    print ("The given substring is not present in the string.")

Output:

operator module

In the above program, we can see we have declared one string “str1” and a substring is specified inside the function argument. To run this program we must first need to import the “operator” module and then we can use the operator.contains() function which will search for substring mentioned as the second argument in the given string mentioned as first argument str1 of the function if this function returns true then it will print the substring is present else if it returns false then it will print substring not present. The output can be seen in the above screenshot.

Now let us see another contains() function used in pandas to find the pattern in the string of series using series.str.contains().

Let us demonstrate this function in the below program with syntax.

Syntax:

Series.str.contains(pat, case=True, flags=0, na=nan, regex=True)
  • pat: Parameter to specify the characters or substring or regular expression.
  • case: True, this parameter is set to true as to say this function is case sensitive.
  • flag: It is used for going through the re module.
  • na: Which is always none, to fill values for missing values.
  • regex: This parameter is set to true if the pat parameter is regular expression else it is set to false as pat is a literal string.

Example #3

Code:

import pandas as pd
print("Program to demonstrate contains() function provided by pandas")
print("\n")
sr = pd.Series(['Educba', 'Training', 'Institue', 'Chennai', 'India'])
print("The given series along with its index and type is as follows:")
print(sr)
print("\n")
r = sr.str.contains('Edu')
print(r)

Output:

Python String Contains 4

In the above program, we first need to import pandas to use pandas function series.str.contains(). In the above program, we have created a series using pandas object pd, and each one is given index in the series and we can see it in the output. Then we are using series.str.contains() and we are passing a substring “Edu” which will search in the string of series that was created and declared as “sr” in the above program. Therefore, when we print the result of the function then it will print the Boolean values of each string in the series along with index number as to in which string the given substring is present it will result in true else it will return false.

Conclusion

In this article, we conclude that the contains() function of string in Python is used in many different ways and is provided in different modules also and this function working is the same such as to find the substring or string in another string. In this article, we saw how the string _contains_() function is used and how it can be used as a class method of string class. In this article, we also saw modules like operator and pandas also provide contains() function. We saw in pandas it is used to find the pattern or substring in the string of series created using pandas object and respective examples are given for demonstration.

Recommended Articles

We hope that this EDUCBA information on “Python String Contains” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. Python SystemExit
  2. Python Dump
  3. Python NameError
  4. Python OS Module
GOLANG Course Bundle - 6 Courses in 1
23+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
iOS DEVELOPER Course Bundle - 61 Courses in 1
147+ Hours of HD Videos
61 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA SERVLET Course Bundle - 18 Courses in 1 | 6 Mock Tests
56+ Hours of HD Videos
18 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
RED HAT LINUX Course Bundle - 5 Courses in 1
28+ Hours of HD Videos
5 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Popular Course in this category
PYTHON for Machine Learning Course Bundle - 39 Courses in 1 | 6 Mock Tests
 125+ Hour of HD Videos
39 Courses
6 Mock Tests & Quizzes
  Verifiable Certificate of Completion
  Lifetime Access
4.8
Price

View Course
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more