Articles

How to Check if a String Contains a Substring in Python

Published Jan 7, 2025Updated Apr 24, 2025
Learn how to check whether a Python string contains a substring, covering different methods, case-insensitive checks, and comparisons between methods.

In today’s digital world, text surrounds us everywhere: web pages, datasets, documents, and more. A common task when working with text is searching for specific words or patterns. Imagine that you need to find a specific word or pattern in a large chunk of text on a webpage, in a dataset, or within a report. In such cases, Python’s substring functionality offers easy-to-use tools that make these searches both fast and straightforward.

In this guide, we’ll walk through the most commonly used techniques to check if a Python string contains a substring. We’ll also discuss how to perform case-insensitive checks and compare the strengths, limitations, and applications of each method.

Let’s start by discussing how we can use the Python in operator to check whether a string contains a substring.

Check Python string contains substring using the in operator

The in operator in Python provides a clean and efficient way to check for the presence of a substring within a string. Depending on whether the substring is present or not, it returns a result in Boolean format: True if the substring is present and False otherwise.

Here is an example of how the in operator is used to search for a substring in a string:

# Define a string
text = "Welcome to Codecademy!"
# Define a substring
substring = "to"
# Use the in operator to check if the string contains the substring
if substring in text:
print("Substring found!")
else:
print("Substring not found!")

Since the substring is present in the string, the code produces this output:

Substring found!

Next, we’ll learn how to use the string .index() method to check for a substring in a Python string.

Related Course

Learn C#: References

Unlock the power of references, an essential aspect of object-oriented programming in C#. Try it for free

Check Python string contains substring using the .index() method

The .index() method is an inbuilt method in Python that allows us to search for a substring within a string. If the substring exists, the method returns the position or index of the first occurrence of the substring. If the substring does not exist, a ValueError is raised.

Here is the syntax for the .index() method:

str.index(substring, start=0, end=len(str)) 

In the syntax:

  • str: The string in which to search for the substring.
  • sub: The substring to be searched within str.
  • start (Optional): Indicates the position in the string where the search should begin.
  • end (Optional): Defines where the search should stop. If not provided, the search continues till the end of the string.

Let’s look at an example of using the .index() method to find a specific substring within a string:

# Define a string
text = "Codecademy is helpful!"
# Define a substring
substring = "is"
# Use the .index() method to check if the string contains the substring
position = text.index(substring)
# Print the result
print("Substring found at index:", position)

Since the substring is present in the string and it starts from index 11, the code produces this output:

Substring found at index: 11

In the next section, we’ll discover how to use the string .find() method to check for a substring in a string.

Check Python string contains substring using the .find() method

The .find() method in Python is another built-in method that we can use to locate substrings within a string. This method checks the main string and returns the index of the first occurrence of the given substring, just like .index(). If the substring is not present, it returns -1. This enables effective handling of the substring without causing an error, unlike the .index() method which raises a ValueError.

The syntax for the .find() method is:

str.find(sub[, start[, end]]) 

Let’s look at an example that uses the .find() method to search for a substring inside a string:

# Define a string
text = "Codecademy loves coding!"
# Define a substring
substring = "coding"
# Use the .find() method to check if the string contains the substring
position = text.find(substring)
if (position != -1):
print("Substring found at index:", position)
else:
print("Substring not found in the main string.")

Since the substring is present in the string and it starts from index 17, the code produces this output:

Substring found at index: 17

Let’s move on to the next method on the list, which is the Python .contains() method.

Check Python string contains substring using the .contains() method

In Python, the .contains() method in the operator module offers the same functionality as the in operator but in a function form. This can be specifically useful in scenarios where we need to pass the containment logic as a callable. For example, when working with higher-order functions like filter(), or when designing functional-style code that requires operations to be expressed as functions rather than operators.

This method takes a string and a substring as arguments and searches for the substring in the main string. If the substring is present, it returns True; otherwise False.

Here is the syntax for the .contains() method:

import operator 

operator.contains(str, substr) 
  • str: The string in which to search for the substring.
  • substr: The substring to search for in str.

Next, let’s go through an example that uses the .contains() method to check for a substring in a string:

import operator
# Define a string
str = "Students love Codecademy!"
# Define a substring
substr = “Codecademy”
# Use the `.contains()` method to check if the string contains the substring
print(operator.contains(str, substr))

Since the substring is present in the string, the code produces this output:

True

In all the methods that we’ve discussed so far, we’ve kept matching cases for strings and substrings. But what happens if the cases don’t match?

Let’s discuss that in the next section.

Performing case-insensitive checks

Python’s case sensitivity can make substring searches challenging at times and result in mismatches. This is where case-insensitive checks come in. Case-insensitive substring searches in Python are essential for guaranteeing accurate and flexible string matching, particularly in situations where the format of the text input can change.

Here’s why this approach is beneficial:

  • Flexibility in user input: Users may input text in various cases, such as “hi”, “Hi”, or “HI”. Case-insensitive searches guarantee that each of these variations is handled similarly, increasing the search’s accessibility and usability.
  • Error tolerance: Ignoring capitalization allows systems to recognize words regardless of how they are typed, making searches more efficient. This approach enhances usability and flexibility, especially in search bars and platforms like forums or online shopping websites, where users often input text in various formats.
  • Efficient string matching: Using case-insensitive methods like .lower() or .upper() simplifies code by eliminating the need for extra logic to handle case variations, making the code cleaner and easier to maintain.
  • Application in real-world scenarios: Majority of search engines employ case-insensitive checks to deliver relevant search outcomes, irrespective of the user’s query capitalization.

Next, we’ll understand how we can use the .lower() and .upper() methods to perform case-insensitive checks in Python.

Let’s check out the .lower() method first.

Using the string .lower() method

The built-in .lower() method in Python converts all the characters of a string to lowercase. This method is especially helpful for case-insensitive string comparisons and searches because it maintains consistency and avoids mismatches resulting from different capitalizations by ensuring all characters are lowercase.

Let’s look at an example of how to use the .lower() method for case-insensitive string searches:

# Define a string
text = "Codecademy offers a lot of courses!"
# Define a substring
substring = "Offers"
# Convert both strings to lowercase for comparison
if substring.lower() in text.lower():
print(f"The substring is found!")
else:
print(f"The substring is not found.")

In this example, both text and substring are converted to lowercase using .lower() to eliminate case differences.

Here is the output:

The substring is found!

Using the string .upper() method

Python’s built-in .upper() method converts all characters of a string to uppercase. When performing case-insensitive string comparisons or searches, this can be quite useful as it eliminates inconsistency brought on by different capitalization in the strings.

Let’s see how the .upper() method improves effective substring searches with the help of an example:

# Define string
text = "Codecademy has a lot of free resources too!"
# Define a substring
substring = "FREE"
# Convert both strings to uppercase for comparison
if substring.upper() in text.upper():
print(f"The substring is found!")
else:
print(f"The substring is not found.")

Here, the case discrepancies are eliminated using .upper() by converting both the original string (text) and the substring (substring) to uppercase.

The code will result in this output:

The substring is found!

Next, let’s compare the pros, cons, and applications of all the string search methods that we’ve discussed till now.

Comparing Python string search methods

Here is a table that compares all these string search methods to provide a better sense of when to use each:

Method Pros Cons Applications
in Checks whether a substring exists in a string and returns a Boolean value. Does not provide the index position of the substring. Best for quick searches.
.index() Used for substring searches and raises a ValueError if the substring is not found. Produces an exception and handles missing substrings inadequately. Preferred when an exception should be raised due to missing substrings.
.find() Finds the first occurrence of a substring and returns its index or -1 if not found. Does not raise an exception, but may not be ideal for handling absent substrings elegantly. Preferred when missing substrings should not cause an exception.
.contains() Functional equivalent of in, useful in functional programming or custom filter logic. Less readable than in for simple substring checks. Ideal for use in higher-order functions like filter() or map().

Conclusion

Python makes it easy to check whether a string contains a specific substring, offering several tools to match a variety of use cases. If we’re looking for a quick and readable way to check for the presence of a substring in a string, the in operator is our best bet. For more detailed checks, like finding the position of the substring or avoiding exceptions, methods like .find(), .index(), and .contains() come into play.

If you want to learn more about strings and string operations in Python, check out the Learn Python 3 course on Codecademy.

Frequently Asked Questions

1. Is the in operator case-sensitive?

Yes, the in operator is case-sensitive. For example, “Apple” in “Pineapple” returns False because of the capital “A”.

2. Can I check if a string contains multiple substrings at once?

Yes, by combining multiple in checks with and:

str = “I like apples and bananas.
print("apple" in str and "banana" in str) # Output: True

3. Is there a performance difference between in and .find()?

The performance is generally similar for small strings, but in is often preferred over .find() for readability and simplicity.

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team