In this Python tutorial, we will discuss everything on Python find substring in string with a few more examples.
Python provides several methods to find substrings in a string. Here we will discuss 12 different methods to check if Python String contains a substring.
- Using the in operator
- Using The find() method
- Using the index() method
- Using the re module
- Using the startswith() method
- Using the endswith() method
- Using the split() method
- Using the partition() method
- Using the count() method
- Using the rfind() method
- Using the list comprehension
- Using the re.findall()
Method-1: Using the in operator
The in operator is one of the simplest and quickest ways to check if a substring is present in a string. It returns True if the substring is found and False otherwise.
# Define the main string
string = "I live in USA"
# Define the substring to be searched
substring = "USA"
# Use 'in' operator to check if substring is present in string
if substring in string:
print("Substring found")
else:
print("Substring not found")
The above code checks if a given substring is present in a given string.
- The main string is stored in the variable string and the substring to be searched is stored in the variable substring.
- The code uses the in operator to check if the substring is present in the string. If it is, the code outputs “Substring found” to the console. If not, the code outputs “Substring not found”.
Read: Slicing string in Python + Examples
Method-2: Using The find() method
The find()
method is another simple way to find substrings in a string. It returns the index of the first occurrence of the substring in the string. If the substring is not found, it returns -1.
# Define the main string
string = "I live in USA"
# Define the substring to be searched
substring = "USA"
# Use the find() method to get the index of the substring
index = string.find(substring)
# Check if the substring is found
if index != -1:
print("Substring found at index", index)
else:
print("Substring not found")
The above code uses the find() method to search for the index of a given substring in a given string.
- The find() method is used to search for the index of the substring in the string, and the result is stored in the variable index.
- If the substring is found, the index will be set to the index of the first character of the substring in the string. If the substring is not found, index will be set to -1.
- The code then checks if index is not equal to -1. If it is not, the substring was found and the code outputs “Substring found at index” followed by the value of the index.
- If the index is equal to -1, the substring was not found and the code outputs “Substring not found”.
Read: Convert string to float in Python
Method-3: Using the index() method
The index() method is similar to the find() method, but it raises a ValueError exception if the substring is not found in the string.
# Search for substring in a given string
string = "I live in USA"
# The substring we want to search for
substring = "live"
# Use try-except block to handle potential ValueError if substring is not found
try:
# Find the index of the substring in the string using the index() method
index = string.index(substring)
# Print a success message with the index of the substring
print("Substring found at index", index)
except ValueError:
# If the substring is not found, print a message indicating that it was not found
print("Substring not found")
The code above is checking if a given substring is present in a string.
- The input string is “I live in USA” and the substring we want to search for is “live”.
- The code uses a try-except block to handle the potential error of not finding the substring in the string.
- The index() method is used to find the index of the substring in the string. If the substring is found, the code prints a message indicating the index of the substring in the string.
- If the substring is not found, a ValueError is raised, which is caught by the except block, and a message indicating that the substring was not found is printed.
Read: Append to a string Python + Examples
Method-4: Using the re module
The re (regular expression) module provides powerful methods for matching and searching for substrings in a string.
# Use the re module for pattern matching
import re
# The string we want to search in
string = "I live in USA"
# The substring we want to search for
substring = "in"
# Use the search() method from the re module to find a match
match = re.search(substring, string)
# Check if a match was found
if match:
# If a match was found, print a success message
print("Substring found")
else:
# If no match was found, print a failure message
print("Substring not found")
The code above is checking if a given substring is present in a string using regular expressions (regex).
- The first line import re imports the re module which provides functions for pattern matching in strings.
- The input string is “I live in USA” and the substring we want to search for is “in”. The code then uses the re.search() method to find a match between the substring and the input string.
- The re.search() method returns a match object if there is a match between the substring and the input string, otherwise it returns None.
- The code then uses an if statement to check if a match was found. If a match was found, the code prints a message indicating that the substring was found.
- If no match was found, the code prints a message indicating that the substring was not found.
Read: Python compare strings
Method-5: Using the startswith() method
The startswith() method returns True if the string starts with the specified substring and False otherwise.
# The string we want to search in
string = "I live in USA"
# The substring we want to search for
substring = "I"
# Use the startswith() method to check if the string starts with the substring
if string.startswith(substring):
# If the string starts with the substring, print a success message
print("Substring found")
else:
# If the string does not start with the substring, print a failure message
print("Substring not found")
The code above checks if a given substring is at the beginning of a string.
- The input string is “I live in USA” and the substring we want to search for is “I”. The code uses the startswith() method to check if the input string starts with the substring.
- The startswith() method returns True if the input string starts with the substring and False otherwise. The code then uses an if statement to check the result of the startswith() method.
- If the input string starts with the substring, the code prints a message indicating that the substring was found. If the input string does not start with the substring, the code prints a message indicating that the substring was not found.
Read: Python program to reverse a string with examples
Method-6: Using the endswith() method
The endswith() method is similar to the startswith() method, but it returns True if the string ends with the specified substring and False otherwise.
# The string we want to search in
string = "I live in USA"
# The substring we want to search for
substring = "USA"
# Use the endswith() method to check if the string ends with the substring
if string.endswith(substring):
# If the string ends with the substring, print a success message
print("Substring found")
else:
# If the string does not end with the substring, print a failure message
print("Substring not found")
The code above checks if a given substring is at the end of a string.
- The input string is “I live in USA” and the substring we want to search for is “USA”. The code uses the endswith() method to check if the input string ends with the substring.
- The endswith() method returns True if the input string ends with the substring and False otherwise. The code then uses an if statement to check the result of the endswith() method.
- If the input string ends with the substring, the code prints a message indicating that the substring was found. If the input string does not end with the substring, the code prints a message indicating that the substring was not found.
Read: Python string formatting with examples.
Method-7: Using the split() method
The split() method splits a string into a list of substrings based on a specified delimiter. The resulting substrings can then be searched for the desired substring.
# The string we want to search in
string = "I live in USA"
# The substring we want to search for
substring = "USA"
# Split the string into substrings using the split() method and store the result in a list
substrings = string.split(" ")
# Check if the substring is in the list of substrings
if substring in substrings:
# If the substring is in the list, print a success message
print("Substring found")
else:
# If the substring is not in the list, print a failure message
print("Substring not found")
The code above checks if a given substring is contained within a string.
- The input string is “I live in USA” and the substring we want to search for is “USA”. The code splits the input string into substrings using the split() method and stores the result in a list substrings.
- The split() method splits a string into substrings using a specified delimiter (in this case, a space character).
- Next, the code uses the
in
operator to check if the substring is in the list of substrings. If the substring is in the list, the code prints a message indicating that the substring was found. - If the substring is not in the list, the code prints a message indicating that the substring was not found.
Method-8: Using the partition() method
The partition() method splits a string into a tuple of three substrings: the substring before the specified delimiter, the specified delimiter, and the substring after the specified delimiter.
# The string we want to search in
string = "I live in USA"
# The substring we want to search for
substring = "I"
# Use the partition() method to split the string into three parts
before, delimiter, after = string.partition(" ")
# Check if the first part of the split string is equal to the substring
if before == substring:
# If the first part is equal to the substring, print a success message
print("Substring found")
else:
# If the first part is not equal to the substring, print a failure message
print("Substring not found")
The code above checks if a given substring is at the beginning of a string.
The input string is “I live in USA” and the substring we want to search for is “I”. The code uses the partition() method to split the input string into three parts:
- The part before the specified delimiter, the delimiter itself, and the part after the delimiter. In this case, the delimiter is a space character.
- The partition() method returns a tuple with three elements: the part before the delimiter, the delimiter itself, and the part after the delimiter.
- The code uses tuple unpacking to assign the three parts to the variables before, delimiter, and after.
- Next, the code uses an if statement to check if the first part of the split string (i.e., before) is equal to the substring.
- If the first part is equal to the substring, the code prints a message indicating that the substring was found. If the first part is not equal to the substring, the code prints a message indicating that the substring was not found.
Method-9: Using the count() method
The count() method returns the number of times a substring appears in a string.
# The string we want to search in
string = "I live in USA"
# The substring we want to search for
substring = "live"
# Use the count() method to count the number of times the substring appears in the string
count = string.count(substring)
# Print the result
print("Substring found", count, "times")
The code above counts the number of times a given substring appears in a string.
- The input string is “I live in USA” and the substring we want to search for is “live”. The code uses the count() method to count the number of times the substring appears in the string.
- Finally, the code uses the print() function to print the result, indicating how many times the substring was found in the string.
Method-10: Using the rfind() method
The rfind() method is similar to the find() method, but it returns the index of the last occurrence of the substring in the string. If the substring is not found, it returns -1.
# The string we want to search in
string = "I live in USA"
# The substring we want to search for
substring = "USA"
# Use the rfind() method to find the last index of the substring in the string
index = string.rfind(substring)
# Check if the substring was found
if index != -1:
# If the substring was found, print the index
print("Substring found at index", index)
else:
# If the substring was not found, print a message
print("Substring not found")
The code above searches for the last occurrence of a given substring in a string.
- The input string is “I live in USA” and the substring we want to search for is “USA”. The code uses the rfind() method to find the last index of the substring in the string.
- The rfind() method returns the index of the last occurrence of the substring in the string, or -1 if the substring is not found. So the code checks if the returned value is not equal to -1, indicating that the substring was found in the string.
- Finally, the code uses the print() function to print the result, indicating the index of the last occurrence of the substring in the string.
Method-11: Using the list comprehension
# The string we want to search in
string = "I live in USA"
# The substring we want to search for
substring = "USA"
# Use a list comprehension to find if the substring exists in the string split into words
result = [word for word in string.split() if word == substring]
# Check if the result list is not empty
if result:
# If the result list is not empty, the substring was found
print("Substring found")
else:
# If the result list is empty, the substring was not found
print("Substring not found")
The code above checks if a given substring exists in a string.
- The input string is “I live in USA” and the substring we want to search for is “USA”. The code uses a list comprehension to create a list of words from the input string, where each word is checked if it is equal to the given substring.
- The list comprehension iterates over the words in the input string, which is split using the split() method, and adds the word to the result list if it is equal to the given substring.
- Finally, the code uses an if statement to check if the result list is not empty. If the result list is not empty, it means that the substring was found in the input string, so the code prints “Substring found”.
- If the result list is empty, the substring was not found in the input string, so the code prints “Substring not found”.
Method-12: Using the re.findall()
The re.findall() function returns a list of all non-overlapping matches of the specified pattern within the string. We can use this function to find all occurrences of a substring within a string by specifying the substring as the pattern.
# Import the regular expression library 're'
import re
# The input text to search for the substring
text = "I live in USA"
# The substring to search for in the text
substring = "USA"
# Find all occurrences of the substring in the text using the 'findall' method from the 're' library
result = re.findall(substring, text)
# Print the result
print(result)
In the above code, the regular expression library re is imported and used to find all occurrences of the given substring “USA” in the input text “I live in USA”.
- The re.findall method is used to search for all occurrences of the substring in the text and return them as a list.
- Finally, the result is printed on the console.
You may like the following Python examples:
- How to concatenate strings in python
- Find Last Number in String in Python
- Find first number in string in Python
- Encode function in Python string
In this Python tutorial, we learned, Python find substring in string using the below methods:
- Python find substring in string using the in operator
- Python find substring in string using The find() method
- Python find substring in string using the index() method
- Python find substring in string using the re module
- Python find substring in string using the startswith() method
- Python find substring in string using the endswith() method
- Python find substring in string using the split() method
- Python find substring in string using the partition() method
- Python find substring in string using the count() method
- Python find substring in string using the rfind() method
- Python find substring in string using the list comprehension
- Python find substring in string using the re.findall()
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.