Check If String Contains Substring In Python

String operations are an important part of programming. One of the most popular strings operating is checking if a string contains a specified substring. From another point of view if the given string exists in the specified string. Python provides different ways to check if the string contains a substring. In this tutorial, we will examine how to check if a given string contains a specified substring in Python.

Check with in Operator

The easieast and most pratical way to check if string contains a substring in PYthon is using the in operator. The in operator is used to check if the specified data exist in the complete data which can be easily used for strings. This check returns True or False according to the situation.

mystring = "pythontect"
substring="tect"

if substring in mystring:
   print("tect exist in pythontect")
else:
   print("tect do not exist in pythontect")

Check with String.index() Method

Python string type provides the index() method in order to find the index of the specified string. The index method is provided by the string variables or string data and returns a positive number if the specified string contains provided substring. If the specified string does not contain a given substring the result is a ValueError exception which means the specified string does not contain the given substring.

mystring = "pythontect"
substring="tect"

try:
   mystring.index(substring)
except ValueError:
   print("Not found")
else:
   print("Given substring found in given string")

Check with String.find() Method

The another method provided by the String type is the find() method. The find() method is very similar the the index() method. The specified substring is searched in the given string and if it is found the index number if the first character is returned. If not found -1 is returned to express it is not found. The String.find() method is easier to use than the index() method.

mystring = "pythontect"
substring="tect"

if mystring.find(substring)>-1:
   print("tect exist in pythontect")
else:
   print("tect do not exist in pythontect")

Check with Regex(Regular Expression)

Regular Expression or simply Regex is used to match a text or string for the specified string. Regex is used by defining patterns and search in the specified text or string. Regex can be also used to find if the string contains a specified substring. The regex module is named re in Python. The search method provided by the re module is used to match regular expressions.

import re

mystring = "pythontect"
substring="tect"

if re.search(substring,mystring):
   print("tect exist in pythontect")
else:
   print("tect do not exist in pythontect")

Leave a Comment