A parser must look for a delimiter that might not exist.
What You Need to Understand
Both find() and index() search for a substring and return its first matching position. The key difference occurs when the substring is missing: find() returns -1, while index() raises ValueError. Both support optional start and end limits.
When to Use It
A parser must look for a delimiter that might not exist.
Step-by-Step Python Example
message = "order:ready"
print(message.find(":"))
print(message.find("#"))
try:
print(message.index("#"))
except ValueError:
print("Delimiter not found")
How the Example Works
The colon is at position five; the missing hash gives -1 from find(). The index() call is caught instead of ending the program.
Example Output
5
-1
Delimiter not found
True
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
value = "@username"
position = value.find("@")
print(position != -1)
Important Behavior and Edge Cases
Never treat find() result as a boolean; position zero is valid but falsy, while -1 is truthy.
Try It Yourself
Search for a colon at the beginning of a new sample and compare both methods.
Common Beginner Mistakes
- Never treat
find()result as a boolean; position zero is valid but falsy, while -1 is truthy. - Applying a string method before defining whether text is intended for display, comparison, parsing, or input validation.
Key Takeaways
- Both
find()andindex()search for a substring and return its first matching position. - The colon is at position five; the missing hash gives
-1fromfind(). - Never treat
find()result as a boolean; position zero is valid but falsy, while -1 is truthy.