Test Index

Python Revision Tour Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 24 of 102
Marks: +1, -0
Differentiate between find() and index() with respect to strings in Python. Give supporting examples for both.
[CBSE 2026 Compartment]
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.
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.
Example:
s = "Python Programming"
print(s.find('o')) # 4
print(s.find('z')) # -1
print(s.index('o')) # 4
print(s.index('z')) # ValueError: substring not found
Here '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
Advertisements
Go to Question: