Tutorial

Python Check If String Contains Another String with Examples

Practical guide: how to check if a string contains a substring in Python using in, find, index, and re.search; covers case-insensitive checks, special characters, and when to choose each method.

Drake Nguyen

Founder · System Architect

3 min read
Python Check If String Contains Another String with Examples
Python Check If String Contains Another String with Examples

Introduction

If you need to verify whether one string appears inside another in Python, this guide explains the most common, safe ways to perform that check. Whether your goal is a quick boolean test or to locate the position of a substring, you'll learn idiomatic approaches such as the in operator, str.find(), str.index(), and regular expressions with re.search(). Keywords covered include "python check if string contains substring", "python string contains", and "python substring check".

Common methods to check for substrings

1. Using the in operator (membership test)

The simplest and most readable way to check if one string contains another is the membership test with the in operator. It returns a boolean and internally calls the __contains__() method.

# quick boolean check
text = "I love Python programming"
sub = "Python"
print(sub in text)  # True

For a case-insensitive membership test without regex, normalize both strings first:

# case-insensitive without regex
print(sub.lower() in text.lower())        # True
# or use casefold() for more aggressive caseless comparisons
print(sub.casefold() in text.casefold())  # True

2. Using str.find() to get a position

find() returns the index of the first occurrence of the substring or -1 if it is not present. This is handy when you need the position but want to avoid exceptions.

3. Using str.index() when the substring must exist

index() behaves like find() but raises ValueError if the substring is missing. Use it when a missing substring should produce an error.

try:
    pos = s.index("Python")
    print("Position:", pos)
except ValueError:
    print("Substring not found (index raised ValueError)")

4. Using re.search() for pattern-based or case-insensitive checks

Regular expressions let you find patterns, not just literal substrings. re.search() returns a match object when the pattern is found, or None otherwise. Use flags such as re.IGNORECASE to make the search case-insensitive.

import re
text = "Learning Python is fun!"
match = re.search(r"python", text, re.IGNORECASE)
print(bool(match))  # True

To check for a literal substring that may contain regex metacharacters (for example $ or .), escape it first with re.escape():

pattern = re.escape("$10.99")
print(bool(re.search(pattern, "Price: $10.99")))  # True

Which method should you use?

  • in: Best for a clear boolean check (python check substring exists in string using in operator). Fast, readable, and no exceptions.
  • find(): Use when you want an index or -1 if not found (python find substring in string and return index).
  • index(): Use when absence should be treated as an exceptional condition; it raises ValueError (python index method substring ValueError).
  • re.search(): Use for pattern matching, case-insensitive checks, or when you need regex features (python re.search check if substring exists).

Handling special cases

  • Case-insensitive checks without regex: use str.lower() or str.casefold() to normalize both strings before testing (python contains substring ignore case; python substring check ignoring case without regex).
  • Special characters in the substring: escape them with re.escape() before using regex (python substring check with re.escape; python contains substring special characters).
  • Checking for whole words: use word-boundary regex like r"\bword\b" to avoid matching substrings inside other words (python check if string contains word).
  • Start-of-string checks: use str.startswith() or a regex anchored with ^ (python check substring start of string).

FAQ

How Netalith I check if a string contains another string in Python?

Use the in operator for a boolean test (e.g., sub in text), or use find()/index() if you also need the position. For pattern matching, use re.search().

What is the difference between in, find(), and index()?

in returns a boolean. find() returns an integer index or -1. index() returns an index but raises ValueError if not found. Choose based on whether you need the position or want exceptions.

How can I perform a case-insensitive check?

Either normalize both strings (text.lower() / text.casefold()) and use in, or use re.search(..., re.IGNORECASE) for regex-based checks.

When should I use regular expressions?

Use regex when you need pattern matching (wildcards, character classes, anchors) or when substrings include special characters that need advanced handling. For literal substring checks, prefer in or find() (python check if string contains substring without regex).

How Netalith I search for a substring that contains regex metacharacters?

Escape the substring with re.escape() before using it in a regex. This treats metacharacters like $, ., or ? as literals.

Conclusion

To summarize, "python check if string contains substring" can be implemented in multiple ways depending on your needs: use in for simple membership tests, find() or index() when you need the position, and re.search() when you require pattern matching or flags such as re.IGNORECASE. For case-insensitive checks without regex prefer lower() or casefold(). These approaches cover use cases from quick boolean checks to advanced substring searches across Python projects.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.