Python String Index: How to Get String Index in Python
The index() method in Python is almost the same as the find() method; the only difference is that the find() method returns -1 if that value is not found.
Python String Index
Python String index() is a built-in function that returns the index of a substring inside the string if found. If the substring is not found, it raises an exception. First, the index() method finds the first occurrence of the specified value. Then, the index() method raises the exception if the value is not found.
Syntax
See the following syntax.
string.index(value, start, end)
Arguments
The value parameter is required, which is the value we search for.
The start parameter is optional; it is Where to start the search. The default is 0.
The end parameter is optional; it is where to end the search. The default is to the end of the string.
Example
Let’s see the following example.
# app.py data = 'Expecto Patronum' extract = data.index('num') print(extract)
See the output below.
If a substring exists inside the string, it returns the lowest index where the substring is found.
If substring doesn’t exist inside the string, it raises a ValueError exception.
More Examples
Let’s find a character between positions. See the below code.
# app.py app = 'We can do whatever we want' sample = app.index('w', 5, 20) print(sample)
See the output below.
If the value is not found, the index() method will raise an exception. See the below example.
# app.py venom = 'We can do whatever we want' carnage = venom.index('z') print(carnage)
The z character is not there in the above code, so that it will return an exception.
That’s it for this tutorial.