Python string contains for finding substrings
Python string contains uses the in operator to check whether a substring appears in text.
Use it when you need a quick yes/no test to route logic, validate input, or filter messages.
It provides a simple, readable way to test whether text contains a substring.
Python String Contains Example For Text Matching
Output:
Output will appear here...
Output:
send tracking
How This Example Works
- The
statusstring holds a short status message. - The expression
"shipped" in statusperforms a substring membership test and returnsTrue. - Because the condition is true, the
printcall runs. - The output shows the action only triggers when the keyword is present.
Common Mistakes
Mistake 1: Assuming the check is case-insensitive.
subject = "Order Shipped"
if "shipped" in subject:
print("send tracking")
subject = "Order Shipped"
if "shipped" in subject.casefold():
print("send tracking")
Why it happens: in compares characters exactly, so letter case must match. Normalize both strings (often with casefold()) when you want case-insensitive contains checks.
Mistake 2: Using find() in a truthy check.
message = "promo"
if message.find("pro"):
print("flag")
message = "promo"
if "pro" in message:
print("flag")
Why it happens: find() returns the index, and index 0 is falsy even when the substring is found. Use in for a boolean contains check, or compare find() to -1 if you need the index.
Mistake 3: Forgetting that empty strings always match.
needle = ""
text = "invoice 123"
if needle in text:
print("match")
needle = ""
text = "invoice 123"
if needle and needle in text:
print("match")
Why it happens: Python treats the empty string as a substring of every string. Guard against empty input when it should mean “no match”.
string contains vs find: Which to Use
| Need | Use |
|---|---|
| Only a yes/no answer | needle in text |
| The position of the match | text.find(needle) |
| An error when missing | text.index(needle) |
Use in for the fastest and clearest membership test. Use find() or index() only when you also need the match position or want a failure to raise an error.
Performance Considerations
A string contains check scans the text linearly, so each in test is O(n) in the length of the text. For repeated case-insensitive checks, normalize the text once (for example, text = text.casefold()) and reuse it to avoid extra work. If you must search for many different patterns in very large strings, consider more specialized search or regex only when the pattern needs it.
When to Use Python string contains
- You need a quick substring check to decide which branch of logic to run.
- You are validating input by looking for required keywords or markers.
- You want the clearest possible boolean test instead of an index result.
- You do not need wildcards or complex patterns; for those, use
re. - You do not need the match position; if you do, use
find()orindex()instead.