Python | Check if a Substring is Present in a Given String
In this article, we will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check if a substring is there in the given string or not.
Example 1: Input : Substring = "geeks" String="geeks for geeks" Output : yes Example 2: Input : Substring = "geek" String="geeks for geeks" Output : yes
Does Python have a string containing the substring method
Yes, Checking a substring is one of the most used tasks in python. Python uses many methods to check a string containing a substring like, find(), index(), count(), etc. The most efficient and fast method is by using an “in” operator which is used as a comparison operator. Here we will cover different approaches like:
- Using the if… in
- Checking using the split() method
- Using find() method
- Using “count()” method
- Using the index() method
- Using __contains__” magic class.
- Using regular expressions
Method 1: Check substring using the if… in.
Yes! it is present in the string
Method 2: Checking substring using the split() method
Checking if a substring is present in the given string or not without using any inbuilt function. First split the given string into words and store them in a variable s then using the if condition, check if a substring is present in the given string or not.
Method 3: Check substring using the find() method
We can iteratively check for every word, but Python provides us an inbuilt function find() which checks if a substring is present in the string, which is done in one line. find() function returns -1 if it is not found, else it returns the first occurrence, so using this function this problem can be solved.
Method 4: Check substring using “count()” method
You can also count the number of occurrences of a specific substring in a string, then you can use the Python count() method. If the substring is not found then “yes ” will print otherwise “no will be printed”.
Method 5: Check substring using the index() method
The .index() method returns the starting index of the substring passed as a parameter. Here “substring” is present at index 16.
Method 6: Check substring using the “__contains__” magic class.
Python String __contains__(). This method is used to check if the string is present in the other string or not.
Yes! Geeks-13 is containing. Yes! Geeks-78 is containing.
Method 7: Check substring using regular expressions
RegEx can be used to check if a string contains the specified search pattern. Python has a built-in package called re, which can be used to work with Regular Expressions.
NO,string 'geeks' is not present in string 'A geek in need is a geek indeed'
Method: Using list comprehension
Method: Using lambda function
Method: Using countof function