Test Index
CBSE Class 12 Computer Science 2026 Paper Compartment
© examsnet.com
Question : 22 of 37
Marks:
+1,
-0
Differentiate between
find() and index() with respect to strings in Python. Give supporting examples for both.
Solution:
Concept:Both methods search a string for a substring and return the index (position) of its first occurrence. They differ only in what happens when the substring is not found.
Example:
| find() | index() |
| Returns the lowest index of the substring if found. | Returns the lowest index of the substring if found. |
| Returns -1 if the substring is not found. | Raises a ValueError exception if the substring is not found. |
| Safe to use without exception handling. | Should be used inside try-except when the substring may be absent. |
s = "Python Programming"print(s.find('o')) # 4print(s.find('z')) # -1print(s.index('o')) # 4print(s.index('z')) # ValueError: substring not foundHere 'o' first occurs at index 4 (P=0, y=1, t=2, h=3, o=4), so both methods return 4. For 'z', which is not in the string, find() returns -1 while index() stops the program with ValueError.© examsnet.com
Go to Question: