Home Python Methods to check if a Python string contains a substring

Methods to check if a Python string contains a substring

Strings are a collection of characters enclosed in single or double quotes in Python. You may need to verify if a string contains a substring during various string manipulation operations. Further, you may check if a string contains a substring using the IN keyword and the IF statement.

We regularly meet a circumstance in Python web development where we must identify whether a specific member from a given list is a sub-string or not. It is another common occurrence in the Machine Learning industry. We will have a look at some choices for doing so.

We’ll also verify if a python string has a substring in this Python article. These include various Python methods for determining whether a text contains a substring. Further, we examine the different strategies and discuss their applications in depth. Each has its own set of uses, benefits, and drawbacks, some of which may be found in Python’s String containing a substring.

Ways to check for a substring in a python string:

  • Using the in operator
  • Using the index() approach
  • Using the find() methods
  • Using the String Methods
  • Using the count() method
  • Using Regular expressions

Why would you want to see if a Python string has a substring?

We check if a python string has a substring for various reasons, but conditional statements are the most typical application. In this situation, a specific code is executed. Another popular application is to determine the index of a substring within a string.

The contains function is most likely something you’ve seen in other programming languages. However, the contains method is also supported by Python. Additionally, it includes a couple of ways to check if a Python string consists of a faster and more understandable substring. We’ll take a look at these in more detail later.

Using the ‘in’ operator

The in operator is the most straightforward pythonic technique to determine whether a Python string includes a substring. The membership operators in and not intakes two arguments and determine whether one is a member of the other. They give you a boolean answer.

Only the in method can determine whether a python string contains a substring. If you need to know the substring index, the following solution can help. It is a faster alternative to the has method, and it may also be used to see if an item in a list exists.

in has the following syntax:

substring in string

The syntax for ‘not in’ is the same as it is for in. To see if a Python string has a substring, we will use the following code:

if "Code" in "Codeunderscored is the best coding site":
  print("Exists")
else:
  print("Does not exist")

Because the in operator is case sensitive, the above code would have returned false if the substring was “code,” therefore using it with the.lower() technique is a good idea. This approach lowers the case of the string. It would not affect the original string because strings are immutable.

if "code" in "Codeunderscored is the best coding site".lower():
  print("Exists")
else:
  print("Does not exist")

String methods in action

Python has a few string methods for determining whether or not a string contains a substring. We’ll look at the search() and index () methods, among the other ways. These methods locate and return the substring’s index. They do, however, have a few drawbacks, which we shall go over in detail.

Making use of the index ()

The string returns the starting index of the substring passed as a parameter.index() function. It returns a ValueError if the substring does not exist is a huge disadvantage. A Try Except can be used to fix this problem. index() has the following syntax:

string.index(value, start, stop)

The value is the substring, and the string refers to the python string. There are two possible options in the syntax: start and stop. These accept index values and aid in searching for a substring within a given index range. Index() is used in the following code:

string = "Codeunderscored is the best coding site."
sti="Code"

try:
    "Codeunderscored is the best coding site".index("Code")
except ValueError:
    print("Does not exist")
else:
    print(string.index(sti))

To avoid arising issues, make sure you use the.lower() function instead of index() which is case sensitive.

try:
    "Codeunderscored is the best coding site".lower().index("Code")
except ValueError:
    print("Does not exist")
else:
    print(sting.index(sti))

Using find()

Another method that we might use to check our query is find(). find() returns the starting index of the substring in the same way as index () does. Find(), on the other hand, returns -1 if the substring does not exist. The leftmost character’s negative index is -1.

find() has the following syntax:

string.find(value, start, end)

parameter definition

  • substring: a substring in a string that needs to be found.
  • start (optional): The starting point for searching for the substring within the string.
  • end(optional): It is the position in the string where the suffix has to be found.

If start and end indexes are not specified, 0 is used as the start index, and length-1 is used as the end index by default. find() has the same syntax and parameters as index(). As a result, find() is used in the following code:

if "Codeunderscored is the best coding site".find("Code") != -1:
    print("Codeunderscored is the best coding site".find("Code"))
else:
    print("Does not exist")

And, once again, find() is case sensitive, requiring the usage of the.lower() method.

if "Codeunderscored is the best coding site".lower().find("code") != -1:
    print("Codeunderscored is the best coding site".find("Code"))
else:
    print("Does not exist")

Example: using find()

str="Hello, its Codeunderscored!"
if str.find("underscored")!=-1:
  print("Found the string")
else:
  print("Not found!!!")

# Substring is searched between start index 2 and end index 5
print(str.find('its', 2, 5))

# Substring is searched start index 8 and end index 18
print(str.find('its ', 8, 18))

# How to use find()
if (str.find('gloomy') != -1):
    print ("Contains given substring ")
else:
    print ("Doesn't contain the given substring")

Although using the str.find() method is less Pythonic, it is still acceptable. It’s a little lengthier and more perplexing, but it gets the job done.

Regular Expressions in Python

For pattern matching, regular expressions are commonly employed. re is a built-in library in Python that may be used to interact with Regular Expressions. The search() function in the re module is used to see if a string contains the supplied search pattern. The syntax for using the regular expressions is as follows:

re.search(pattern, string, flags[optional])

code sample:

from re import search
str="Codeunderscored is all about coding!"
substring = "red"
if search("coding", str):
    print ("Substring Found!")
else:
    print ("Not found!")

Example: using regex to find a substring

from re import search

string = "Codeunderscored.com"
substring = ".com"

if search(substring, string):
    print("Found")
else:
    print("Not found")

When doing sophisticated operations on strings, use the other methods over REGEX covered in this post since they are much faster.

Counting strings with the str.count() method

The Python count() function counts the number of times a given substring appears in a string. The function returns 0 if the substring is not found in a string.

str ="Condeunderscored is all about coding."

str.count("coding")
str.count("Coding")

function __contains__()

The contains() function of the Python String class is used to see if it contains another string. The contains () method is called internally when we employ the Python “in” operator; the has () method is called internally.

Although methods that begin with underscores are regarded semantically private, the in operator is recommended for readability. When class instances exist on the right side of the in and not in operator, the contains method describes how they act. We could also use this function directly, but we won’t.

What are the Caveats and Limitations?

Because all methods are case-sensitive, remember to utilize the.lower() techniques. The index() method ensures that it is placed inside a try-except condition.

Example: using List comprehension

In our initial example, we will use list comprehension. List comprehension is a technique for determining whether or not a string contains a substring from a list. We check for both list and string entries in this example to see if we can find a match, and if we can, it returns true.

The code below shows how to use list comprehension to determine whether a text contains a list element. To begin, the string named first str has been created. After that, the test list called fruits_list is created. For your convenience, we printed the original principles_message string and list before completing the function. Then we used list comprehension to see if the string included the list element and published the result.

principles_message = "Two students in the classroom will each take up two Bananas."

fruits_list = ['Mango', 'Bananas']

print("Principles message : " + principles_message)

print("List of fruits : " + str(fruits_list ))

the_result = [ele for ele in fruits_list  if(ele in principles_message)]

print("Is there a list element in the string? " + str(bool(the_result)))

Example: Check to see if a Substring is found several times in a String

The count() function in the String class is used to check if the string contains a substring twice.

count() returns a number the number of times it appears in the string and 0 if the substring is not available in the string. Check if the count is equal to two to see if it exists twice.

string = "codeunderscored is a site dedicated to code."

if string.count("code") ==2:
  print("code exists twice in the string")
else:
  print("code doesn't exist twice in the string")

Example: Check to see if the string contains any substrings from the list

You may need to see if a string has one of a list’s multiple substrings. For example, you could need to see if the given string has any vowels. You can do this in Python by using the List comprehension and the any() method.

The ability to comprehend lists will return True if the iterated item is found in the String. On the other hand, If the current repeated item is not found in the String, False is returned. Overall, the result will be a list of True or False statements.

The any() method will then verify at least one True value in the generated list. If Yes, the string has at least one vowel. If the answer is no, the string is devoid of vowels.

#Code Snippet

string = "Codeunderscored is a site dedicated to code"
vowel_list = ['a','e','i','o','u']
if any(substring in string for substring in vowel_list):
print("Vowels exists in the string")
else:
print("Vowels doesn't exist in the string")

Example: Find all of a substring’s indexes

The finditer() method in the regular expression package is used to find the index of every occurrence of a substring in a string. Import the regular expression package with import re to use it. To find all substring indexes in a string, use the procedure below.

# Code Snippet

import re
string = "codeunderscored is a site dedicated to code"
matches = re.finditer("code",string)
indexes = [match.start() for match in matches]
print(indexes)

Example: Count the number of times a substring appears.

The count() method counts the number of times a substring appears in a string. The method count() is responsible for returning the number of times it appears in the string or 0 if the substring does not exist.

# Code Snippet

string = "codeunderscored is a site dedicated to code"
substring = "code"
print(string.count(substring))

Conclusion

One of the most common duties in any programming language is to see if a string contains a substring. As a result, several techniques exist to verify if a string includes a substring in Python.

Remember that the in operator is the most straightforward way to determine whether a string contains a substring. In addition, the “in” operator, which is used as a comparison operator, is the simplest and fastest way to verify whether a string includes a substring or not in Python. Other Python functions, such as find(), index (), count(), and so on, can also be used to determine whether a string contains a substring.

You may also like

Leave a Comment