String find() Method in Python

Python String find() Method

The find() method in Python is used to find the first occurrence of a substring within a given string. It returns the index of the first occurrence of the substring if found, and if the substring is not present, it returns -1.Here's the syntax of the find() method:

string.find(substring, start, end)

Parameters:

  • substring: The substring that you want to find within the original string.
  • start (optional): The index from which the search for the substring begins. It is an optional parameter, and if not provided, the search starts from the beginning of the string.
  • end (optional): The index at which the search for the substring ends. It is an optional parameter, and if not provided, the search goes until the end of the string.

Example:

# Example string
original_string = "Hello, world!"

# Finding the index of the substring "world" in the string
index = original_string.find("world")

print("Original String:", original_string)
print("Index of 'world':", index)

Output:

Original String: Hello, world!
Index of 'world': 7

In this example, we used the find() method to find the index of the substring "world" in the original string. The method returned 7, which is the index of the first character of the substring "world" within the original string.If the substring is not found in the string, the find() method returns -1. For example:

# Example string
original_string = "Hello, world!"

# Finding the index of the substring "Python" in the string
index = original_string.find("Python")

print("Original String:", original_string)
print("Index of 'Python':", index)

Output:

Original String: Hello, world!
Index of 'Python': -1

In this case, since the substring "Python" is not present in the original string, the find() method returns -1.