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 foundindex()returns the position, but raises an error if not foundinreturns onlyTrueorFalse
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
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
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:
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 not in
text = "banana"
if "xyz" not in text:
print("missing")
Step by step:
textis"banana".- Python checks whether
"xyz"appears in the string. - It does not find it.
"xyz" in textwould beFalse.- Therefore
"xyz" not in textisTrue. - 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.
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()returns0when the substring starts at the beginning0is treated asFalsein 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
| 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") | Index as integer | Raises ValueError | Missing substring should be treated as an error |
in vs find()
- Use
inwhen you only need yes/no - Use
find()when you need the starting position
find() vs index()
find()is safer when absence is normalindex()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.
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:
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.
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.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.