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
Facing issues? Have Questions? Post them here! I am happy to answer!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- How to convert int to ASCII in Python
- How to make use of SQLite Module in Python?
- Split a String into Sub-string and Parse in Python
- Python: Pandas Rename Columns with List Example
- How to run Python file from Mac Terminal
- How to Exit a Loop in Python Code
- Python: How to Plot a Histogram using Matplotlib and data as list
- MD5 Hashing in Python
- Jupyter: Safari Cant Connect to the Server localhost:8888/tree
- Fix: AttributeError: str object has no attribute decode. Did you mean: encode?[Python]
- How to Read a binary File with Python
- How to add two float numbers in Python
- Python: How to install YAML Package
- Python: How to Save Image from URL
- What is Markdown in Jupyter Notebook with Examples
- How to change the Python Default version
- 33: Python Program to send an email vid GMail
- How to comment code in Python
- How to Fix AttributeError in Python
- Fix: error: Jupyter command `jupyter-nbconvert` not found [VSCode]
- How to comment out a block of code in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- Import Other Python Files Examples
- Python: How to add Progress Bar in Console with Examples
- 3 Ways to convert bytes to String in Python
- Enable Versioning on SharePoint Online Site Task List - SharePoint
- How to take a screenshot on Microsoft Windows OS on PC or Laptop - Microsoft
- Java: How to Add two Maps with example - Java
- [Fix] Connect to Minecraft Remote Connect URL via https //aka.ms/remoteconnect - Microsoft
- Convert text to random case using Notepad++ - NotepadPlusPlus
- Annual Surveys that Software Developers Should Look for! - News
- Delete Android Studio Projects - Android-Studio
- Save TextEdit file as a PDF - MacOS