Open In App

Python String find() Method

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

find() method in Python returns the index of the first occurrence of a substring within a given string. If the substring is not found, it returns -1. This method is case-sensitive, which means "abc" is treated differently from "ABC". Example:

Python
s = "Welcome to GeekforGeeks!"
index = s.find("GeekforGeeks")
print(index)

Output
11

Explanation: The substring "GeeksforGeeks" starts at index 11 in the string "Welcome to GeeksforGeeks!". Hence, find() method returns 11

Syntax of find() method

s.find(substring, start, end))

Parameter:

  • substring: The substring to search for within the main string s.
  • start (optional): The starting index from where to begin the search.
  • end (optional): The ending index where the search should stop.

Return Value:

  • Returns the first index of the substring if it is found within the specified range.
  • Returns -1 if the substring is not found.

Examples of find() method

Example 1: We can limit the search to a specific portion of the string by providing start and end parameters.

Python
s = "abc abc abc"
index = s.find("abc", 4)
print(index)

Output
4

Explanation:

  • The search starts from index 4, skipping the first "abc".
  • The next occurrence of "abc" is found at index 8.

Example 2: The find() method is case-sensitive, so uppercase and lowercase letters are treated differently.

Python
s = "Python is fun"
index = s.find("python")
print(index)

Output
-1

Explanation: Since "python" (lowercase) does not match "Python" (uppercase), the method returns -1.

Example 3: In this example, we are searching for the first occurrence of a substring "abc" in a string that contains multiple spaces between the words.

Python
s = "abc   abc   abc"
res = s.find("abc")
print(res)

Output
0

Explanation: The substring "abc" starts at index 0 in the string "abc abc abc", so find() returns 0.

find() vs index()

Both find() and index() methods locate a substring within a string. However, they differ in behavior when the substring is not found.

  • find() returns the index or -1 if not found
  • index() same as find(), but raises a ValueError if not found

To learn more, please refer to "Difference Between find( ) and index( ) in Python".

Related Articles:


Next Article
Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy