Question

Python String Contains: How to Check for a Substring in Python

pythonstringsubstringcontains

Question

I want to know whether Python has a string.contains() or string.indexOf() style method for checking if one string appears inside another.

For example, I want logic like this:

if not somestring.contains("blah"):
    continue

What is the correct Python way to check whether a string contains a substring?

Short Answer

By the end of this page, you will understand the Python way to test whether a string contains a substring. You will learn why the in operator is usually the best choice, when find() is useful, how this differs from methods like contains() in other languages, and how to avoid common mistakes.

Concept

In Python, the most common way to check whether a string contains another string is the in operator.

"blah" in somestring

This returns:

  • True if the substring exists
  • False if it does not

Python does not use string.contains() as the normal built-in way to do this. Instead, substring checks are written using a very readable expression:

if "blah" in somestring:
    print("Found it")

This matters because substring checks appear everywhere in real programs:

  • validating user input
  • filtering text
  • searching logs
  • processing files
  • checking URLs, headers, and API responses

Python also provides string methods like find() and index(), but they are slightly different:

  • find() returns the position of the substring, or -1 if not found
  • index() returns the position, but raises an error if not found
  • in returns only True or False

If your goal is simply to know whether the substring exists, in is the clearest and most Pythonic option.

Mental Model

Think of a string as a long strip of text, like a sentence written on paper.

Using in is like asking:

“Does this piece of paper contain the word blah anywhere?”

You are not asking where it appears. You only care whether it is present.

  • "blah" in somestring → asks yes or no
  • somestring.find("blah") → asks at what position
  • somestring.index("blah") → asks at what position, but complains if missing

So:

  • use in for a simple existence check
  • use find() when you also need the position
Take Quiz

Syntax and Examples

The most common syntax is:

substring in string

To check that a substring is not present:

substring not in string

Basic example

text = "hello world"

print("world" in text)      # True
print("python" in text)     # False
print("python" not in text) # True

Explanation:

  • "world" in text is True because those characters appear in order
  • "python" in text is False because that substring does not exist
  • not in is the cleanest way to check for absence

Your example written in Python style

if "blah" not in somestring:
    continue

This is the direct Python equivalent of the code you wanted.

Using find()

text = "hello world"

position = text.find("world")
print(position)  # 6

missing = text.find("python")
print(missing)   # -1

Use find() when you need the starting index.

Using index()

text = "hello world"

print(text.index("world"))  # 6

But this raises an error if the substring is missing:

text.index("python")
# ValueError: substring not found

Case-sensitive behavior

text = "Hello World"

print("hello" in text)  # False
print("Hello" in text)  # True

String containment in Python is case-sensitive.

Case-insensitive check

text = "Hello World"

print("hello" in text.lower())  # True

A safer version when both sides may vary in case:

text = "Hello World"
needle = "HELLO"

print(needle.lower() in text.lower())  # True

Step by Step Execution

Consider this code:

text = "banana"

if "ana" in text:
    print("found")
else:
    print("not found")

Step by step:

  1. text is assigned the value "banana".
  2. Python evaluates "ana" in text.
  3. It checks whether the sequence of characters a, n, a appears anywhere inside "banana".
  4. It finds "ana" starting at index 1.
  5. The expression becomes True.
  6. Because the condition is true, Python runs:
print("found")

Output:

found

Another trace with not in

text = "banana"

if "xyz" not in text:
    print("missing")

Step by step:

  1. text is "banana".
  2. Python checks whether "xyz" appears in the string.
  3. It does not find it.
  4. "xyz" in text would be False.
  5. Therefore "xyz" not in text is True.
  6. Python prints:
missing

Real World Use Cases

Substring checks are used constantly in real programs.

Validating input

email = "user@example.com"

if "@" not in email:
    print("Invalid email address")

Filtering log lines

line = "ERROR: database connection failed"

if "ERROR" in line:
    print("Important log entry")

Checking file names

filename = "report.pdf"

if ".pdf" in filename:
    print("This looks like a PDF")

Detecting keywords in text

message = "Your order has shipped"

if "shipped" in message:
    print("Send tracking update")

Working with URLs or API responses

url = "https://example.com/api/users"

if "/api/" in url:
    print("API endpoint detected")

These examples show why in is so useful: it makes intent obvious and keeps code short.

Take Quiz

Real Codebase Usage

In real codebases, developers usually choose substring checks based on what they need next.

Simple boolean checks

Use in when all you need is true/false.

if "Bearer " not in auth_header:
    raise ValueError("Missing token prefix")

Guard clauses

A common pattern is to exit early when expected text is missing.

def parse_line(line):
    if ":" not in line:
        return None
    key, value = line.split(":", 1)
    return key.strip(), value.strip()

Validation

def is_basic_email(value):
    return "@" in value and "." in value

Case-insensitive checks for user-facing text

def contains_keyword(text, keyword):
    return keyword.lower() in text.lower()

When position matters

Developers use find() when they need the index for slicing or parsing.

line = "name=alice"
position = line.find("=")
if position != -1:
    key = line[:position]
    value = line[position + 1:]

Error handling with index()

index() is less common for simple checks because it raises ValueError if the substring is absent. It is more suitable when missing data should be treated as an actual error condition.

Common Mistakes

1. Looking for a nonexistent contains() method

Broken code:

if somestring.contains("blah"):
    print("found")

Why it fails:

  • Python strings do not normally use a built-in contains() method for this style

Correct version:

if "blah" in somestring:
    print("found")

2. Using find() incorrectly in a condition

Broken code:

text = "hello world"

if text.find("hello"):
    print("found")

Why this is a problem:

  • find() returns 0 when the substring starts at the beginning
  • 0 is treated as False in a condition
  • so this code can incorrectly skip a match

Correct version:

if text.find("hello") != -1:
    print("found")

Or better:

if "hello" in text:
    print("found")

3. Forgetting case sensitivity

Broken expectation:

text = "Hello"
print("hello" in text)  # False

Fix:

print("hello" in text.lower())  # True

4. Confusing substring search with whole-word matching

text = "catapult"
print("cat" in text)  # True

This is correct, but it may be surprising if you wanted only the whole word cat.

For whole-word matching, you may need splitting or regular expressions depending on the problem.

5. Using index() without handling missing values

Broken code:

text = "hello"
print(text.index("z"))

This raises:

ValueError: substring not found

Use in or find() if the substring may be missing.

Comparisons

ApproachReturnsIf not foundBest use
"x" in textTrue / FalseFalseSimple containment check
"x" not in textTrue / FalseTrueSimple absence check
text.find("x")Index as integer-1Need the position safely
text.index("x")Index as integerRaises ValueErrorMissing substring should be treated as an error

in vs find()

  • Use in when you only need yes/no
  • Use find() when you need the starting position

find() vs index()

  • find() is safer when absence is normal
  • index() is stricter when absence should fail loudly

Python vs other languages

Some languages use methods like:

  • contains()
  • indexOf()

Python usually expresses the same idea more directly:

"needle" in haystack

That is one reason Python code often reads more like plain English.

Take Quiz

Cheat Sheet

Quick substring checks

"sub" in text       # True if present
"sub" not in text   # True if absent

Get position

text.find("sub")    # returns index or -1
text.index("sub")   # returns index or raises ValueError

Recommended choice

  • Need True/False only → use in
  • Need the index → use find()
  • Need the index and want an error if missing → use index()

Case sensitivity

"Hello" in "Hello world"   # True
"hello" in "Hello world"   # False

Case-insensitive version:

needle.lower() in text.lower()

Common Python version of your example

if "blah" not in somestring:
    continue

Important edge case

"" in "abc"   # True

The empty string is considered to be contained in every string.

FAQ

Is there a contains() method for Python strings?

The usual Python way is to use the in operator, not contains().

How do I check if a string contains a substring in Python?

Use:

substring in text

How do I check that a substring is not in a string?

Use:

substring not in text

What is the difference between in and find() in Python?

in returns True or False. find() returns the starting index or -1.

Is Python string matching case-sensitive?

Yes. "Hello" and "hello" are different unless you normalize case yourself.

When should I use index() instead of find()?

Use index() when a missing substring should be treated as an error. Otherwise, find() or in is usually better.

Does in work only for strings?

No. Python also uses in with lists, tuples, sets, dictionaries, and other containers.

What happens if I search for an empty string?

The empty string is considered present in any string, so "" in text returns True.

Take Quiz

Mini Project

Description

Build a small text filter that checks whether certain keywords appear in a list of messages. This demonstrates practical substring checks using in and not in, which is a common task in scripts, moderation tools, and log processing.

Goal

Create a Python program that scans messages and labels them based on whether they contain selected keywords.

Requirements

  • Create a list of sample messages.
  • Check whether each message contains the word error in a case-insensitive way.
  • Print ALERT for matching messages.
  • Print OK for non-matching messages.
  • Use the in operator for the substring check.
Take Quiz

Keep learning

Related questions

View more