Python String index() Method Tutorial

In this section, we will learn what String index() method is and how to use it in Python.

What is String index() Method in Python?

The Python string index() method is used to search for a value in a string.

Basically, this method takes a string value as its argument and returns the position (index number) of the first occurrence where the same value was there in the target string.

Note: an exception will be thrown if the target string did not have the specified value!

Python String index() Method Syntax:

string.index(value, start, end)

String index() Method Parameter

The method takes 3 arguments:

  • The first argument is the string value that we want to search for in the target string.
  • The second argument is the index number where we want to start the search for the specified value. This value is optional and, if ignored, the value 0 will be used.
  • The third argument is the index number where we want to stop the search for the specified value. This value is also optional and, if ignored, the size of the target string value will be used instead.

String index() Method Return Value

The return value of this method is the index number, where the first occurrence of the specified value is.

Note: an exception will return if there’s no occurrence for the specified value.

Example: python string indexof

s1 = "They know we know that they know we know!"

result = s1.index("know")

print(result)

Output:

5
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies