In this tutorial, you will learn various methods to check whether a string contains a different string.
Strings in Python are basically byte arrays that are used for representing Unicode characters. Strings are usually represented as letters surrounded by single or double quotation marks.
For example, “Hey” is a string.
Performing string operations are very common among coders. An important operation in Python is to check whether a string contains another string.
This is possible in Python by given below ways
- Using the "in" Operator
- Using the "find()" Method
- Using the String Contains "__contains__()"
- Using the “count” Method
- Using The String.index() Method
- Using Regular Expressions (REGEX)
- Search Substring in String with Non-Case Sensitive or Case Insensitive
Let’s look at these methods -
1. Using the “in” Operator
The in operator is used for checking whether a value exists within a Python data structure such as a string or list. The in operator returns a Boolean value - True or False.
This is one of the easiest ways to check for a substring within another string in Python.
Returns: Returns True or False
If a value exists, it will return True otherwise False.
Let’s take a look at this example:
# Python program to check if a string contains the substring
# using in operator
# Initializing string
string = 'Hi this is STechies sites'
# Use in operator with if statement
# to check if string contains substring
if 'STechies' in string:
print('String found')
else:
print('String not found')
Output:
String found
The in operator is used to check whether the string “STechies” is within the variable string. The in operator loops through all the characters of the string 'Hi this is STechies sites' for finding the string “STechies”.
As it finds the string within the variable string, the condition within the if statement is evaluated to be True. Hence “String found” is printed to the screen.
2. Using the "find()" Method
The find() method is a convenient method as you will not have to worry about handling exceptions. The method looks for a substring within a larger string.
Python find() method returns the index of the first instance of the string that is to be found. If it does not find it, -1 is returned.
Returns: Integer value
Does not throw exceptions error
Example:
# Python program to check if a string contains the substring
# using find() method
# Initializing string
string = 'Hi this is STechies sites'
# Use find() method with if statement
if string.find('STechies') != -1:
print('String found')
else:
print('String not found')
Output:
String found
Here, the variable called string has a value of 'Hi this is STechies sites'. Inside the if statement find() method to check whether the string “STechies” exists within the variable string. According to the string.find('STechies') != -1 statement, the find function searches for the string “STechies”.
It checks whether the method does not return -1, which means that the string is found. If this condition is not satisfied, it means that the string is not found.
3. Using the String contains "__contains__" Method
The __contains__ () in Python is an object method that checks whether a string object contains the specified string or not. Depending on the search result, it returns a Boolean value, True or False.
Example:
# Python program to check if a string contains the substring
# Using __contains__ method
# Initializing string
string = 'Hi this is STechies sites'
# Use __contains__ with if statement
if string.__contains__('STechies'):
print('String found')
else:
print('String not found')
Output:
String found
The variable called string contains the value 'Hi this is STechies sites'. Then the if statement along with the __contains__() method is used for searching the “STechies” string within the string variable.
The __contains__() method returns True if the string is found, and False if not found. So as the string “STechies” is within the string 'Hi this is STechies sites', the if condition is satisfied and “String found” is printed.
4. Using the “count” Method
The count() method is used to search for a substring in another string. It returns the number of times the substring is present within the larger string. The method has three parameters:
substring - The string that you has to be searched
start - The index where the search begins
stop - The index where the search process ends
The syntax of count() is as follows:
string.count(substring, start, end)
Example:
# Python program to check if a string contains the substring
# using count() method
# Initializing string
string = 'Hi this is STechies sites'
# count method count number of time substring occurs
# in given string between index 0 20
# it returns integer value
# if value is greater then 0
# it will print "Substring found"
print('Number of occurrence of a substring: ',string.count("STechies", 0, 20))
if string.count("STechies", 0, 20) > 0:
print('Substring found')
else:
print('Substring not found')
Output:
Number of occurrence of a substring: 1
Substring found
Here, the string variable called string has a value “Hi this is STechies sites”. Then the count() method is used along with the string print statement. In the line, print(n.count("STechies", 0, 20)) ,
- n is the main string variable
- “STechies” is the substring to be searched
- 0 is the starting index
- 20 is the index where the search ends
As the string “STechies” occurs 1 time between the index 0 and 20, the result 1 is printed as output.
5. Using the String.index() Method
Python provides an index() method that determines the occurrence of a substring in another string. It returns the first position of the substring in another string.
The syntax for this method is:
str.index(str, beg = 0 end = len(string))
Its parameters are:
str - This is the string to be searched
beg - The starting index for searching the string
end - The ending index for searching the string
The string is searched within [start:end], where the end parameter is optional. The method returns the first position of the string that you are searching.
# Python program to check if a string contains the substring
# using index() method
# Initializing string
string = 'Hi this is STechies sites'
# Initializing substring to search
substr = "STechies"
# Using index() method to find position of "STechies"
# starting from 0th index
p = string.index(substr,0)
print ("The Position of STechies : ",p)
Output:
The Position of STechies : 11
In this code, the main string ch has the value "Hi this is STechies sites". The argument string to be searched substr is initialized with the value “STechies”. In the p variable, the value of string.index(substr,0) is assigned.
Here, the index() method is applied on the string variable, where the substring value in substris searched after the zero index.
As the substring appears at the 11th index, the output is printed as: The Position of STechies : 11.
6. Using the Regular Expressions (REGEX)
The REGEX is a Python library that is called re.
This module has a method called search() that is used to search for substrings. The re.search() method is great when you want to perform case insensitive matching, that might be complicated.
Example:
# Python program to check if string contains substring
# using Regular Expressions
import re
# Initializing string
string = 'Hi this is STechies site'
if re.search("STechies", string):
print('String found')
else:
print('String not found')
Output:
String found
In the code written above, the Python library re that stands for Regular Expressions is used. The code makes use of the search() method to look for a string inside another string.
So in the line if re.search("STechies", string), the re.search() method looks for “STechies” inside the string variable. As the statement evaluates to be True, “String found” is printed.
The re.search() method is case-sensitive that returns a math object if the string is found. It returns None if the string is not found.
7. Search Sub-String in String with Non-Case Sensitive or Case Insensitive
You have seen that all the methods above are case sensitive. But in order to search for substrings in other strings where the both uppercase and lowercase characters exist, you have to use some in-built functions.
Functions such as lower() or upper() can be used for making all the string cases same that will ease the search process.
Example:
# Python program to check if string contains substring
# Non-Case Sensitive or Case Insensitive
# Initiate string
string = 'Hi this is STechies sites'
# Initiate substring to search
substring = 'stechies'
# Convert both string and substring to lower case
string = string.lower()
substring = substring.lower()
# Check if substring present in main string
if substring in string:
print('String found')
else:
print('String not found')
Output:
String found
In this example, the code tries to look for a string that is in lower case in another string that has both uppercase and lowercase characters. At first, the variables string and substring are converted to lowercase using the lower() method.
Then using the in operator is used for searching for the substring in the string.
As the substring is found within the main string, “String found” is printed as a result.
Conclusion
You can use various methods for searching strings within another string.
The method will depend upon the length of the string that you are trying to search.
For strings having a smaller length, the in operator is ideal and fast. For larger strings, you can use the find(), __contains__() or the re.search() method.
You can also combine the in operator along with the lower() method for searching for strings.