How To Check If String Contains Substring in Python – Detailed Guide

Python Strings are a sequence of characters enclosed with single quotes or double quotes. During various string manipulation operations, you may need to check if a string contains a substring in it.

You can check if a string contains a substring using the IF statement and IN keyword.

In this method, you’ll learn how to check if String contains a substring.

If You’re in Hurry…

You can use the below code snippet to check if String contains Substring using IF and IN.

Note: This method performs case sensitive check. Ensure you use the right cases.

Snippet

string = "Stackvidhya"

if "Stack" in string: 
    print("Substring Exists")
else:
    print("Substring Not Exists")

Output

    Substring Exists

This is one of the easiest and the fastest methods to check if a String contains a Substring.

If You Want to Understand Details, Read on…

In this tutorial, you’ll learn the different methods available to check if a string contains a specific substring and you’ll also learn the different use cases to use the methods.

Using In

You can check if a String contains a substring using the In statement.

This is the easiest and the fastest method to check if a substring exists in the String.

Note: This method performs case sensitive check. Ensure you use the right cases.

You can use this method if you want to find if the substring exists in a string without Exception handling.

Snippet

string = "Stackvidhya"

if "Stack" in string: 
    print("Substring Exists")
else:
    print("Substring Not Exists")

Output

    Substring Exists

This is how you can use the IN statement to check if a substring is available in a String.

Using Find

In this section, you’ll use the find() method available in the String class to check if a substring exists in the string.

find() method returns,

  • Starting index of the first occurence of substring in the String.
  • -1 if the Substring doesn’t exists in the String

You can use this method if you want to find if the substring exists in a string without Exception handling.

Note: This method performs case sensitive check. Ensure you use the right cases.

Snippet

string = "Stackvidhya"

if string.find("Stack") > -1: 
    print("Substring Exists")
else:
    print("Substring Not Exists")

Output

    Substring Exists

Snippet

A snippet to demonstrate the substring non-existence is given below.

Note: You’re finding the word stack but still you’ll see it doesn’t exist. Because the S in the string is in a different case. Hence the else statement will be executed.

string = "Stackvidhya"

if string.find("stack") > -1: 
    print("Substring Exists")
else:
    print("Substring Not Exists")

Output

    Substring Not Exists

This is how you can use the find() method available in String to check if a substring is available in the String.

Using Index

You can use the index() method available in the String class to find the index of the substring in the string.

It returns the index of the first occurrence of the substring if it exists.

OR

Throws ValueError Exception if the substring doesn’t exist in the string.

Snippet

string = "Stackvidhya"
try:
    print(string.index("Stack"))

    if string.index("Stack") > -1: 
        print("Substring Exists")
except ValueError:
    print ('Substring Not Exists')

First, you’ll see the index of the substring printed and since it is greater than -1, you’ll see the if statement exectued.

Output

    0
    Substring Exists

Snippet

This is to demonstrate the ValueError exception when the substring is not available in the string. You can catch the ValueError exception to handle a scenario that is applicable for the substring non-existence.

string = "Stackvidhya"
try:

    if string.index("stack") > -1: 
        print("Substring Exists")

except ValueError:
    print ('Substring Not Exists')

You’re finding the word stack but still, you’ll see it doesn’t exist. Because the S in the string is in a different case. Hence the Exception block will be executed.

Output

    Substring Not Exists

This is how you can use the index() method available in the string to check if the substring is available in the string.

Now, you’ll see the different use cases and how they can be used to check if a string contains a substring.

Check If String Contains Substring Case Insensitive

As you’ve seen before, all the methods available to check if the string contains a substring performs only case sensitive check.

But you may need to check if a string contains a substring in a case insensitive way.

You can ignore the case while checking if the String contains a substring by converting both the string and a substring to lower case or upper case.

This can be done either by using lower() or the upper() method.

Snippet

string = "Stackvidhya"

if "stack".lower() in string.lower(): 
    print("Substring Exists")
else:
    print("Substring Not Exists")  

During the if check, the source string is converted to lower case. Hence the substring will be checked against, stackvidhya instead of Stackvidhya.

Since both are in the same case now, you’ll see the output saying Substring exists.

Output

    Substring Exists

This is how you can check if a string contains a substring in a case-insensitive way.

Check If String Contains Substring Using Regex

You can use check if String contains substring using regex.

This may be useful when you do not know the substring beforehand or if you want to check if the given string is a valid email address.

For using the regular expressions, first, import the re package using import re.

Then you can use the search() method available in the re package to check if the matching substring is available in the string.

To know more about regular expression, refer regular expression cheat sheet.

In the below example, you’ll check if the string contains a word Stack_. After this word, it may contain any combination of characters.

The search function returns,

  • True – If pattern match is found in the String
  • False – If pattern match is not found

Snippet

import re

string = "Stack_vidhya"
substring = "Stack_*"

if re.search(substring, string):
    print("Substring Exists")
else:
    print("Substring Not Exists")

Output

    Substring Exists

This is how you can use the regular expressions to check if a string contains a substring.

Check If String Contains Substring Multiple Times

You can check if the string contains a substring multiple times using the count() function available in the String class.

count() returns

  • number of times the substring exists in the string
  • 0 if the substring is not available in the string

To check if it exists multiple times, you can use the n_time variable and check if the count is equal to n_time, then it means the string exists for the defined n_times. Else it doesn’t exist defined n_times.

Snippet

string = "Stack_vidhya"

n_times = 3

if string.count("a") ==n_times:
    print("a exists "+ str(n_times) + " times in the string")
else:
    print("a doesn't exists "+ str(n_times) + " times in the string")

Output

    2

This is how you can check if a substring exists multiple times in a string.

Check If Substring Exists Twice In String

You can check if the string contains a substring twice using the count() function available in the String class.

count() returns

  • number of times the substring exists in the string
  • 0 if the substring is not available in the string

To check if it exists twice, you can check if the count is equal to 2.

Snippet

string = "Stack_vidhya"

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

Output

    a exists twice in the string

This is how you can check if a substring is available twice in the string.

Check If String Contains Any Substring From List

You may need to check If a string contains one of the multiple substrings from a list.

For example, you may need to check if any of the vowels exist in the given string.

You can do this by using the List comprehension and the any() method available in python.

List comprehension will return,

  • True – If the current iterated item is available in the String
  • False – If the current iterated item is not available in the String

The resultant list will be having a list of True or Falses

Then the any() method will check if the resultant list contains at least one True. If Yes, means at least one vowel exists in the string. If No, the string doesn’t contain any vowels.

Snippet

string = "Stack_vidhya"

lis = ['a','e','i','o','u']

if any(substring in string for substring in lis):
    print("Vowel exists in the string")
else:
    print("Vowel doesn't exists in the string")

Output

    Vowel exists in the string

This is how you can check if a string contains any substring from the list.

Find All Index of a Substring

You can find the index of every occurrence of a substring in a string using the finditer() method available in the regular expression package.

To use the regular expression package, import it using import re.

Use the below method to find all indexes of a substring in a string.

Snippet

import re

string = "stack_vidhya"

matches = re.finditer("a",string)

indexes = [match.start() for match in matches]

print(indexes)

Output

    [2, 11]

This is how you can find the index of all occurrences of the substring.

Count Substring Occurences

You can count the occurrence of a substring in a string using the count() method.

count() method returns,

  • number of times the substring exists in string
  • 0 if the substring doesn’t exist.

Snippet

string = "stack_vidhya"

substring = "a"

print(string.count(substring))

Output

    2

This is how you can count the number of substring occurrences in a string.

Conclusion

To summarize, you’ve learned the methods available to check if a string contains a substring. You’ve also learned how those methods can be used to check the existence of the substring in various scenarios.

Also, you’ve learned how to find all indexes of a substring and count the substring existence in the string.

If you have any questions, comment below.

You May Also Like

Leave a Comment