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)
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

- How to add two float numbers in Python
- tkinter - Hello World! Program
- Convert Float to String in Python
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- How to List all Packages installed using pip [Python]
- Check if String Contains a Substring - Python
- Change label (text) color in tkinter
- Where does brew install python in macOS
- Validate email address in Python using regular expression (regex)
- How to uninstall pip Python packages
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- Python: Fix command not found pip or pip3 on zsh shell
- Check version of pip package installer for Python
- 3 Python program to add two numbers
- Calculate discount amount python code
- How to add borders to tkinter label text
- How to install Python 3.9 using brew on Mac
- Python Program To Calculate Simple Interest (SimpleInterest.py)
- Comments in Python Programming
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to take user input from the console in a Python program
- Install and Run Jupyter Notebook on Mac (macOS)
- Tkinter - add x and y padding to label text
- 7 Python Arithmetic Operators with Examples [Tutorial]
- Python Sleep Function/Method Code Example
- Notepad++ select all above or below lines - NotepadPlusPlus
- Python Program To Calculate Simple Interest (SimpleInterest.py) - Python
- How to save IntelliJ IDE Console logs to external log file - Android-Studio
- How to Identify installed PowerShell version - Powershell
- [Error] Microsoft Teams: We're sorry—we've run into an issue. - Microsoft