AppDividend
Latest Code Tutorials

Python String Index Example | String.index() Tutorial

0 20

Get real time updates directly on you device, subscribe now.

Python String Index Example | String.index() Tutorial is today’s topic. Python index() method 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

The syntax of index() method for a string is following.

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.

# app.py

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

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.py

app = 'We can do whatever we want'
sample = app.index('w', 5, 20)
print(sample)

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.

# app.py

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

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.