str.index() Find (raises if missing)
Last updated: 2026-09-22
str.index() Find (raises if missing)
str.index(sub) is like find(), but raises ValueError when not found.
| Category | String Methods |
|---|---|
| Kind | Built-in Type Method |
| Python Version | all |
📝 Syntax
str.index(sub[, start[, end]])
⚙️ Parameters
| sub Required | The substring to search for. |
|---|---|
| start Optional | Start index of the range (inclusive); None means the beginning.(Default:None) |
| end Optional | End index of the range (exclusive); None means the end.(Default:None) |
Returns:int. The lowest index where sub is found; raises ValueError if absent.
Mutates the original:No (returns a new object)
💥 Raises
ValueError— Raised when sub is not found in the range.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
2
not found: substring not found
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the difference between index() and find()?
ATheir behavior is almost identical, with one difference: when not found, find() returns -1 while index() raises ValueError: substring not found.
QWhen should I use index()?
AUse index() when the substring "must exist" and not finding it is a logic error, so the exception exposes the problem immediately; otherwise find() is safer.
QHow do I avoid index() raising an exception?
ACheck with in first: if 'll' in s: print(s.index('ll')); or catch ValueError with try/except.