Last modified: Feb 09, 2025 By Alexander Williams

Check Exact Match Substring in Python String

Working with strings is a common task in Python. One frequent requirement is to check if a substring exists in a string. This article explains how to check for an exact match substring in Python.

Why Check for Exact Match Substring?

Checking for an exact match substring is useful in many scenarios. For example, you might need to validate user input or search for specific patterns in text data. Python provides simple methods to achieve this.

Using the in Operator

The simplest way to check if a substring exists in a string is by using the in operator. This operator returns True if the substring is found, otherwise False.


# Example using the 'in' operator
text = "Python programming is fun"
substring = "programming"

if substring in text:
    print("Substring found!")
else:
    print("Substring not found.")


# Output
Substring found!

This method is case-sensitive. If you need a case-insensitive search, convert both strings to the same case using lower() or upper().

Using the find() Method

Another way to check for a substring is by using the find() method. This method returns the index of the first occurrence of the substring. If the substring is not found, it returns -1.


# Example using the 'find()' method
text = "Python programming is fun"
substring = "programming"

index = text.find(substring)

if index != -1:
    print(f"Substring found at index {index}.")
else:
    print("Substring not found.")


# Output
Substring found at index 7.

This method is also case-sensitive. You can combine it with lower() or upper() for case-insensitive searches.

Using Regular Expressions

For more complex substring searches, you can use regular expressions with the re module. This method is powerful and flexible, allowing you to search for patterns rather than exact matches.


# Example using regular expressions
import re

text = "Python programming is fun"
substring = "programming"

if re.search(substring, text):
    print("Substring found!")
else:
    print("Substring not found.")


# Output
Substring found!

Regular expressions are case-sensitive by default. Use the re.IGNORECASE flag for case-insensitive searches.

Conclusion

Checking for an exact match substring in Python is straightforward. You can use the in operator, the find() method, or regular expressions. Each method has its use cases, so choose the one that best fits your needs.

For more Python string manipulation tips, check out our guides on splitting strings and replacing characters in strings.