Python String index() Method
Finding the string(substring) in a string is an application that has many uses in day-to-day life. Python offers this using a function index(), which returns the position of the first occurrence of a substring in a string.
ch.index(ch1, begp, endp)
- ch1 : The string to be searched for.
- begp (default : 0) : This function specifies the position from where search has to be started.
- endp (default : string_len) : This function specifies the position from where search has to end.
Returns the first position of the substring found.
Raises ValueError if argument string is not found.
The first position of geeks after 2nd index : 8
Note: The index() method is similar to find(). The only difference is find() returns -1 if the searched string is not found and index() throws an exception in this case.
Example 2: Exception
ValueError: This error is raised in the case when the argument string is not found in the target string.
Traceback (most recent call last): File "/home/aa5904420c1c3aa072ede56ead7e26ab.py", line 12, in pos = ch.index(ch1) ValueError: substring not found
Practical Application: This function is used to extract the suffix or prefix length after or before the target word. The example below displays the total bit length of instruction coming from AC voltage given information in a string.
The total bit length of AC is : 13
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course