Python find() String Method with Examples

How to Use the Python String find() Method

In this tutorial, we'll learn how to use the Python string find() method.

The string find() method finds the first occurrence of a substring in a given string and returns the index of the substring if found.

Python String find() Syntax:

The syntax of the string find() method is as follows:

string.find(substring, start[, end])

The find() Method Parameters

  • substring: Required. The substring to be searched in the string.
  • start: Optional. The position to start the search. It defaults to 0 if not specified.
  • end: Optional. The position to end the search. It defaults to the end of the string if not specified.

Remarks

  • The find() method returns -1 if a substring is not found in the string.
  • Use the find() method if you want to know the position of a substring. If you just want to check if the substring exists in the string or not, use the in operator. For example: "Tutorial" in "Best Tutorial".

Examples

Example 1

The following sample code returns the index of the first occurrence of Python in the string:

string = "Best Python Programming Tutorials, Python Programming for Beginners, Basic Python Programming."
substring = "Python"
index = string.find(substring)
print ("The index of the first occurrence of Python is", index)

Result:

The index of the first occurrence of Python is 5

Example 2

The following sample code returns the index of the first occurrence of Java in the string:

string = "Best Python Programming Tutorials, Python Programming for Beginners, Basic Python Programming."
substring = "Java"
index = string.find(substring)
print ("The index of the first occurrence of Python is", index)

Result:

The index of the first occurrence of Java is -1

Since the substring Java was not found, the find() method returned -1.

Example 3

The following sample code returns the index of the first occurrence of Java, searching between position 10 and 100:

string = "Best Java Programming Tutorials, Java Programming for Beginners, Basic Java Programming."
substring = "Java"
index = string.find(substring, 10, 100)
print ("The index of the first occurrence of Java is", index)

Result:

The index of the first occurrence of Java is 33

In this tutorial, we've learned how to use the Python string find() method. The string find() method is used to return the position of a substring within a given string. If you want to know if a substring exists in the string, you can use the in operator.


See also:
Python return Statement with Examples
Python List Methods and Functions with Examples
Python abs() – Absolute Value in Python
Python Factorial – Find the Factorial of a Number
Python min() – Find the Smallest Value in Python

Leave a Comment