Python check if string contains substring [9 Methods]

In this Python article, I will explain how Python check if string contains substring or not using different methods. Moreover, we’ll look at a variety of examples Check if a String contains a Substring in Python.

Recently, I have been working on a machine learning project and I have found that it requires some sub-string elements and checking whether it is available in string or not. So, I have done some research and found that we have to Check if a String contains a Substring in Python.

Methods in Python check if string contains substring

In Python, there are numerous ways to check if a string contains a particular substring. In this article, we’ll explore the most common following techniques to achieve this.

  1. If-Else and in-Operator
  2. split() method
  3. find() method
  4. count() method
  5. index() method
  6. list comprehension
  7. lambda function
  8. Slicing Function
  9. regular expressions

Let’s explore all of them one by one using some illustrative examples:

Method 1: Python check if string contains substring using if-else and in operator.

The in operator checks for the presence of one string within another in Python. It returns True if the substring exists and False otherwise. This approach is simple and often the first choice in Python due to its clarity.

Example: Consider a situation where we are checking if the substring is in a sentence stored in Python as a string.

sentence = "I love visiting New York in the fall."
if "New York" in sentence:
    print("The state is mentioned!")
else:
    print("The state isn't mentioned!")

Output: This example checks if the substring is present within the string in Python. Since it is, the output will be:

The state is mentioned!
python check if string contains substring

This way we can use the in operator with an if-else condition, which can help Python check if string contains substrings.

READ:  How to divide two numbers in Python

Method 2: Python string contains substrings using split() method

The split() method in Python divides a string into a list of substrings based on a specified delimiter. If the substring exists within the main string, the length of the resulting list will be greater than 1. If not, the length will be 1.

Scenario: For a case, we have to split a Python string to check for a substring mentioned in it or not.

commentary = "The Yankees hit another home run!"
if len(commentary.split("Yankees")) > 1:
    print("The Yankees are in this commentary!")
else:
    print("The Yankees aren't mentioned!")

Output: Here, the split() method tries to split the string at each occurrence of the substring. If the substring is present in the Python string, the length of the resulting list will be greater than 1.

The Yankees are in this commentary!
which of the following is the correct way to check if a string contains a specific substring in python

The split() function in Python check if string contains substring.

Method 3: String contains Python substring using find() method

The find() method in Python searches for a substring and returns the starting index of the first occurrence. If the substring isn’t found, it returns -1. Thus, by checking the return value, one can determine the presence of the substring.

Example: We are Finding the position of a substring if it is present in the string in Python.

itinerary = "First, we'll visit Miami, then head to Los Angeles."
position = itinerary.find("Los Angeles")
if position != -1:
    print(f"Los Angeles is mentioned, starting at position {position}!")
else:
    print("Los Angeles isn't in the itinerary.")

Output: The find() method searches for the substring and returns its starting index in Python string.

Los Angeles is mentioned, starting at position 39!
python substring contains in a string

This way the find() function can help Python check if string contains substring.

Method 4: Python contains substring using the count() method

The Python count() method calculates how many times a substring appears within a main string. If the count is greater than 0, it means the substring is present in the string in Python.

Scenario: We are in a situation where we have to count how many times a substring is mentioned in the string in Python.

text = "The Grand Canyon is a marvel. I've been to the Grand Canyon twice!"
if text.count("Grand Canyon") > 0:
    print(f"The Grand Canyon is mentioned {text.count('Grand Canyon')} times!")
else:
    print("The Grand Canyon isn't mentioned.")

Output: The count() method calculates the occurrences of substring in the Python string.

The Grand Canyon is mentioned 2 times!
check if a string contains a substring python

The count() function in Python check if string contains substring or not.

READ:  Python Add String to List

Method 5: Check if string contains substring Python using index()

Similar to the find() method, the index() method in Python searches for a substring and returns its starting index. The key difference is that if the substring isn’t found, index() raises a ValueError exception in Python instead of returning -1.

Example: Finding where the mentioned substring is first present in a Python string.

speech = "Today, we discuss various topics. President Biden has emphasized unity."
try:
    position = speech.index("President Biden")
    print(f"President Biden is first mentioned at position {position}.")
except ValueError:
    print("President Biden isn't mentioned in the speech.")

Output: The index() method looks for the first occurrence of the substring in the Python string and returns its starting index.

President Biden is first mentioned at position 34.
python string contains substring

This way we can use the index() function in Python check if string contains substring in it or not.

Method 6: String contains Python substring using list comprehension

The list comprehension in Python involves constructing a list where each element is a section of the main string, with a length equal to the substring. The comprehension checks if any of these sections match the substring. This method, while interesting, may not be the most efficient for longer strings.

Scenario: Checking for the mention of a substring in a string in Python.

dishes = "We have burgers, hot dogs, pizza, and tacos."
burger_present = any([dishes[i:i+len("burgers")] == "burgers" for i in range(len(dishes))])
print("Burgers are on the menu!" if burger_present else "No burgers today.")

Output: This Python code uses list comprehension to check each substring of the length of the mentioned substring and checks if any of them match it.

Burgers are on the menu!
python contain substring

This way we can check if Python string contains substring using list comprehension.

Method 7: Python str contains substring using lambda function

Lambda functions in Python are concise ways to define small functions. Here, we create a lambda function that uses the in operator to check for the presence of the substring in Python.

Example: Consider a situation where we have to in the Python check if string contains substring.

note = "Let's have a party on Thanksgiving!"
contains_holiday = lambda note, holiday: holiday in note
print("Thanksgiving plans are set!" if contains_holiday(note, "Thanksgiving") else "No plans yet for Thanksgiving.")

Output: A lambda function in Python checks the presence of a substring in the string. It’s a reusable variant of the in-operator.

Thanksgiving plans are set!
if string contains python

This way we can have a lambda function in Python check if string contains substring.

READ:  Lambda in List Comprehension in Python [3 Examples]

Method 8: Python contains string with substring using slicing

The slicing in the Python approach is similar to the list comprehension method. It checks every possible slice of the main Python string that has the length of the substring. If any of these slices match the substring, then the substring is present.

Scenario: Searching for a substring in a string through the Python slicing method.

article = "Silicon Valley has many giants, including Apple, Google, and Facebook."
apple_present = any(article[i:i+len("Apple")] == "Apple" for i in range(len(article)))
print("Apple is mentioned in the article!" if apple_present else "Apple isn't mentioned.")

Output: This pile of code uses the slicing technique in Python to check every substring of the length of a string if it matches the substring.

Apple is mentioned in the article!
python if string contains substring

This way the slicing concept in Python can help Python check if string contains substring.

Method 9: Python check if string contains substring using Regular expression

Regular expressions (regex) in Python are powerful tools for text matching. By using the search function from the re-module, one can look for the presence of a pattern (in this case, the substring) within a main string. It’s particularly useful when more complex patterns need to be matched.

Example: Validating a substring is present in a string in Python through re-module.

import re
zip_code = "90210"
if re.search(r"^\d{5}$", zip_code):
    print("Valid ZIP Code format!")
else:
    print("Invalid ZIP Code format!")

Output: This search() from the re module in Python checks if the string contains substring.

Valid ZIP Code format!
check if string contains substring

This way we can use the search() function in the regex module in Python check if string contains substring.

Conclusion

Understanding how Python check if string contains substring or not with nine different methods like If-else within operator, split() method, find() method, count() method, index() method, list comprehension, lambda function, slicing function, and regular expressions search() method. Taking help with some examples I have tried to explain all of them.

Python offers a variety of methods to check if a string contains a substring. Depending on the specific requirement, such as whether one needs to know the index of the substring or just its presence, one can choose the method that best fits their needs.

Also, take a look at some more Python tutorials.