Python String – index() method

This is a method in python that returns the index of the first occurrence of the value. If not found throws an error.

Syntax:

List.index(value, starting_position, ending_position)

Example 1:

s = “code hustle repeat
x = s.index(“hustle“)
print(x)

Output:

1

Explanation:

Here the word “hustle” occurred at index 1. Hence returned 1

Example 2:

s = “code hustle repeat hustle
x = s.index(“hustle“)
print(x)

Output:

1

Explanation:

Here the word “hustle” occurs first at the index 2 overlooking any other futher occurences.

Note:

The difference between index and find is that find returns -1 if the value is not found in the string on the other hand index throws an error if not found.

You Missed
Also Checkout