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 substring in a string.
Syntax : 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.
Return Value : Returns the first position of the substring found.
Exception : 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.
ValueError : This error is raised in the case when the argument string is not found in the target string.
Runtime Error :
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 string.
The total bit length of AC is : 13
- Python Language advantages and applications
- isupper(), islower(), lower(), upper() in Python and their applications
- Python | Multiply each element in a sublist by its index
- Dunn index and DB index - Cluster Validity indices | Set 1
- Designing GUI applications Using PyQt in Python
- Applications and Uses of Selenium WebDriver
- Convert given Pandas series into a dataframe with its index as another column on the dataframe
- System tray applications using PyQt5
- Python String isspace() and its application
- Python String isalpha() and its application
- Python String isdigit() and its application
- Python String isnumeric() and its application
- Python - Characters Index occurrences in String
- Python - Replace to K at ith Index in String
- Python - Remove index ranges from String
- Python - Filter the List of String whose index in second List contaons the given Substring
- Python program to Concatenate Kth index words of String
- Python - Access element at Kth index in given String
- numpy string operations | index() function
- Python | Index of Non-Zero elements in Python list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.