Python String index() and Find() — pythonpip.com

Parvez Alam
2 min readDec 3, 2021

In this tutorial, we will learn about the Python index() method with the help of examples.I also let you know how to do the same thing using find() method.

Python index() Method

The index() method returns the index of a substring inside the string. If the substring is not found, it raises an exception. This method is the same as find(), but raises an exception if sub is not found.

Syntax:Parameters:

  • str: This specifies the string to be searched.
  • beg: This is the starting index, by default its 0.
  • end: This is the ending index, by default its equal to the length of the string.

str.index(str, beg = 0 end = len(string)) Output :

Simple Example:

str = 'Pythonpip is a python tutorial' result = str.index('python') print(result) print(str.index('is a', 10, -4))15 10
  • value: This is a value to search for.
  • start: This is the starting index, by default its 0.
  • end: This is the ending index, by default its equal to the length of the string.

Python Find() Method

The find() method finds the first occurrence of the specified value. This method returns -1 if the value is not found.

Output :

Simple Example:

str = 'Pythonpip is a python tutorial' result = str.find('python') print(result) print(str.index('is a', 10, -4))15 10

Originally published at https://www.pythonpip.com on December 3, 2021.

--

--

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/