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:
Trueif the substring existsFalseif 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-1if not found
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
blahanywhere?”
You are not asking where it appears. You only care whether it is present.
"blah" in somestring→ asks yes or nosomestring.find("blah")→ asks at what positionsomestring.index("blah")→ asks at what position, but complains if missing
So:
- use
infor a simple existence check - use
find()when you also need the position
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 textisTruebecause those characters appear in order"python" in textisFalsebecause that substring does not existnot inis the cleanest way to check for absence
Your example written in Python style
Step by Step Execution
Consider this code:
text = "banana"
if "ana" in text:
print("found")
else:
print("not found")
Step by step:
textis assigned the value"banana".- Python evaluates
"ana" in text. - It checks whether the sequence of characters
a,n,aappears anywhere inside"banana". - It finds
"ana"starting at index1. - The expression becomes
True. - Because the condition is true, Python runs:
print("found")
Output:
found
Another trace with
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
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
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()returns0when the substring starts at the beginning0is treated asFalsein a condition
Comparisons
| Approach | Returns | If not found | Best use |
|---|---|---|---|
"x" in text | True / False | False | Simple containment check |
"x" not in text | True / False | True | Simple absence check |
text.find("x") | Index as integer | -1 | Need the position safely |
text.index("x") |
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/Falseonly → usein - 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:
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 instead of ?
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
errorin a case-insensitive way. - Print
ALERTfor matching messages. - Print
OKfor non-matching messages. - Use the
inoperator for the substring check.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.