Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
python3
strings
communitycreator

What is the difference between String find() and index() method?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

Python provides the following two built-in methods to find the first occurrence of a given substring in a string:

  • find()

  • index()

Both methods have the same syntax. However, in the case where the required substring is not found in the target string, there is a significant difference in the output of both these methods:

  • find() returns -1.

  • index() raises an exception.

find()

Syntax

string_name.find(str, start, end)

Code sample

string = 'Educative shot'
# starts search at index 1 and ends at index 7
print(string.find('ca ', 1, 7))

Note: In the code above, the substring ca has a space after the character a. That’s why the method find() returns -1.

index()

Syntax

string_name.find(str, start, end)

Code sample

txt = "Hello, welcome to Educative."
# Substring to be search
x = txt.index("b")
# display the position
print(x)

Note: In the code above, a ValueError is raised since substring b is not found in the string.

RELATED TAGS

python
python3
strings
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring