If you want to find the substring or character in the string, there are two methods- index()
and find()
.
Both of these methods return the index of the substring if the substring you want to search is present in the given string.
Write a program to find the index of the substring in the given string.
Example of index()
samp_str = "CSEstack programmer"
print(samp_str.index('stack'))
Output:
3
Note: The index()
method can also be used to search the element in the Python list.
Example of find()
We will use the same string and sub-string for find()
method.
samp_str = "CSEstack programmer"
print(samp_str.find('stack'))
Output
3
You will find the same output result.
Is there any difference between index()
and find()
?
Obviously, if these are two methods, there should have some differences.
Let’s search for the sub-string which is not present in the given string.
In the given example, we are searching ‘stock’ instead of ‘stack’ in the given string.
Using index() method
samp_str = "CSEstack programmer"
print(samp_str.index('stock'))
Output:
print(samp_str.index('stock')) ValueError: substring not found
This throws an ValueError
.
Getting runtime error crashes your application. This is not a good practice of coding. You have to handle this exception gracefully.
Either you can handle this exception using try-except block or using find()
method.
How method() is different from index()?
Let’s see.
Using find() method
We are using same string and sub-string.
samp_str = "CSEstack programmer"
print(samp_str.find('stock'))
Output:
-1
When you use find()
method to search the substring which is not present in the given string, it returns -1
.
find()
.index()
method to find the index of the substring, use exception handling to avoid runtime crashes.Related Python Programming Questions:
Hope this guide helps you to find the difference between index()
and find()
in Python. Use them wisely. If you have any doubt, comment below.
Happy Pythoning!