In this article, we will take a look at three different ways various examples in Python to check if a string contains a substring,
- Using the in and not in operator,
- Using the String index() & find() methods,
- Using Regular Expressions,
1. Check Substring using in/not in Operator
This is the most commonly used way in Python to check a string contains the provided substring,
Example:#This is the String
my_string = "This is some text that I want to check for a substring"
#These are the Substrings
my_substring_1 = "check"
my_substring_2 = "code2care"
#Example 1: Found
if my_substring_1 in my_string:
print("String - "+my_substring_1+" found!")
else:
print("String - "+my_substring_1+" not found!")
#Example 2: Not Found
if my_substring_2 in my_string:
print("String - "+my_substring_2+" found!")
else:
print("String - "+my_substring_2+" not found!")
#Example 3: Using not in
if my_substring_1 not in my_string:
print("String - "+my_substring_1+" not found!")
else:
print("String - "+my_substring_1+" found!")
String - check found!
String - code2care not found!
String - check found!
2. Check Substring using String.find() or String.index()
Note that if you use if/else with index(), if there is no match in substring you will get ValueError, so its better to use try with else,
Example: Using String.index(str)#This is the String
my_string = "This is some text that I want to check for a substring"
#These are the Substrings
my_substring_1 = "check"
my_substring_2 = "code2care"
#Example 1: Found
try:
my_string.index(my_substring_1)
except ValueError:
print("String - "+my_substring_1+" found!")
else:
print("String - "+my_substring_1+" not found!")
#Example 2: Not Found
try:
my_string.index(my_substring_2)
except ValueError:
print("String - "+my_substring_1+" found!")
else:
print("String - "+my_substring_1+" not found!")
#Example 3: ValueError: substring not found
if my_string.index(my_substring_2):
print("String - "+my_substring_1+" found!")
else:
print("String - "+my_substring_1+" not found!")
Output:
String - check not found!
String - check found!
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-19-eed4a6b4d213> in <module>()
26 #Example 1: Error
27
---> 28 if my_string.index(my_substring_2):
29 print("String - "+my_substring_1+" found!")
30 else:
ValueError: substring not found
#This is the String
my_string = "This is some text that I want to check for a substring"
#These are the Substrings
my_substring_1 = "check"
my_substring_2 = "code2care"
#Example 1: Found
if my_string.find(my_substring_1) != -1:
print("String - "+my_substring_1+" found!")
else:
print("String - "+my_substring_1+" not found!")
#Example 2: Not Found
if my_string.find(my_substring_2) != -1:
print("String - "+my_substring_2+" found!")
else:
print("String - "+my_substring_2+" not found!")
#Example 3: Not Found
if my_string.find(my_substring_2) == -1:
print("String - "+my_substring_2+" not found!")
else:
print("String - "+my_substring_2+" found!")
3. Check Substring using Regular Expressions (RegEx)
import re
mystring = "Today is a good day!"
substring = r"good"
matches = re.finditer(substring, mystring, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
Output:
Match 1 was found at 11-15: good

Have Questions? Post them here!
- tkinter - Hello World! Program
- How to install Python Specific version (3.8, 3.9 or 3.10) using Brew
- How to install SpaCy (NLP Library) on Mac
- Python matplotlib segmentation fault: 11 macOS Big Sur
- How to uninstall pip Python packages
- 3 Ways to find if element is present in a List in Python
- How to Convert Python String to DateTime Object
- Python f-strings Formatted String Literals Syntax and Examples
- Where does brew install python in macOS
- Take input argument from command line in Python Programming
- Advanced print() Function Tutorial and Techniques for Python Developers
- How to add borders to tkinter label text
- Whats new in Python 3.10 Pre-release
- Float built-in function in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- How to check if Key Exists in Python Dictionary?
- Read a file line by line in Python Program
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- What is the Max and Minimum Value of int type in Python?
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- Fix: TypeError: can only concatenate str (not int) to str in Python
- How to take user input from the console in a Python program
- [Fix] TypeError: str object is not callable in Python
- 3 Python program to add two numbers
- How to delete a file using Python code example
- [Fix] Modern authentication failed here, but youll still be able to sign in. Your status code is 4c7 - Microsoft Teams - Teams
- Download Google Chrome setup exe file using PowerShell - Powershell
- Cannot load PowerApps form in SharePoint Online due to repeated authentication - SharePoint
- [Java] NoClassDefFoundError Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory - Java
- Truncate table using Java JDBC Example - Java
- Gradle FAILURE: Build failed with an exception - Task not found in root project - Gradle
- How to Select All text in vim/vi editor using Keyboard - Linux
- Display full website URL/address in Safari macOS Browser - MacOS