Latest Code Tutorials

Python String Index Example | String.index() Tutorial


Python String index() is an inbuilt function that returns the index of a substring inside the string if found. If the substring is not found, it raises an exception.  The index() method finds the first occurrence of the specified value. The index() method raises the exception if the value is not found. An index() method is almost the same as the find() method, the only difference is that find() method returns -1 if that value is not found.

Python String Index Example

See the following syntax.

string.index(value, start, end)

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.

Let’ s see the following example.


data = 'Expecto Patronum'
extract = data.index('num')

See the output below.

Python String Index Example

If substring exists inside the string, it returns the lowest index in the string 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 = 'We can do whatever we want'
sample = app.index('w', 5, 20)

See the output below.

String Index() Tutorial

If the value is not found, then the index() method will raise an exception. See the below example.


venom = 'We can do whatever we want'
carnage = venom.index('z')

In the above code, the z character is not there, so it will return an exception.

More Examples on String Index Method

Finally, Python String Index Example | String.index() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.