Why This Happens
str.index() raises ValueError when not found, while str.find() returns -1. The same applies to list.index(). Use 'in' to check existence first.
The Problem
text = 'Hello, World!'
pos = text.index('Python')The Fix
text = 'Hello, World!'
pos = text.find('Python') # Returns -1 if not found
# Or: if 'Python' in text: pos = text.index('Python')Step-by-Step Fix
- 1
Use find() instead
str.find() returns -1 when not found.
- 2
Check with 'in'
Use 'substring' in string to check existence first.
- 3
Handle the exception
Wrap in try/except ValueError.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free