What is the operator.indexOf() method in python?
What is the operator module?
The operator module is an built-in module in python. The module provides functions equivalent to the intrinsic operators of python. For example, we can use the operator.mul() method to multiply instead of the * operator.
The module’s functions come in handy when callable methods are given as arguments to another Python object.
The indexOf() method
The indexOf() method takes two parameters. The syntax of the method is as follows:
operator.indexOf(a, b)
The method is used to return the index of the first occurrence of b in a. a here is iterable.
If b is not in a then the method raises a ValueError indicating b is not in a.
Code
import operatora = "hello educative"b = "e"print("operator.indexOf('%s', '%s') = %s" % (a, b, operator.indexOf(a, b)))a = [1, 2, 3, 4]b = 5try:print("operator.indexOf('%s', '%s') = %s" % (a, b, operator.indexOf(a, b)))except ValueError as ex:print("%s not in %s" % (b, a))
Explanation
In the code above,
- Line 1:
operatormodule is imported. - Lines 3-4: Two strings
aandbare initialized. - Line 6: The index of
binais obtained using theindexOf()method and the result is printed. - Lines 8-9: New values for
aandbare assigned. - Lines 11-14: The index of
binais obtained using theindexOf()method. But the method throws aValueErrorindicating that5is not present in[1, 2, 3, 4].