Python str.find() function


str.find() Function in Python

The str.find() function in Python is used to search for a specified substring within a string and return the index (position) of its first occurrence. If the substring is not found, it returns -1. This function is useful for checking the presence of a substring in a string and determining its position.

Syntax:

string.find(substring, start, end)
  • substring: The substring you want to search for.
  • start (optional): The starting index from where the search should begin. The default is 0.
  • end (optional): The ending index where the search should stop. The default is the end of the string.

Example 1: Basic usage

# Example 1: Finding a substring my_string = "Hello, world!" index = my_string.find("world") print(index) # Output: 7

In this example:

  • The substring "world" is found at index 7 in the string "Hello, world!".

Example 2: Substring not found

# Example 2: Substring not found my_string = "Hello, world!" index = my_string.find("Python") print(index) # Output: -1

Here:

  • The substring "Python" is not found in the original string, so the result is -1.

Example 3: Specifying start and end indices

# Example 3: Specifying start and end indices my_string = "Hello, world! Welcome to the world of Python." index = my_string.find("world", 10) print(index) # Output: 27

In this case:

  • The search for "world" starts from index 10, and the first occurrence of "world" after that is found at index 27.

Example 4: Using find() with overlapping substrings

# Example 4: Overlapping substrings my_string = "banana" index = my_string.find("ana") print(index) # Output: 1

Here:

  • The substring "ana" is found starting at index 1.

Key Points:

  • str.find() returns the index of the first occurrence of the specified substring.
  • It is case-sensitive, meaning "Hello" and "hello" are considered different.
  • If the substring is not found, it returns -1.
  • You can specify optional start and end parameters to limit the search range within the string.
  • The function does not modify the original string.

Example 5: Case sensitivity

# Example 5: Case sensitivity my_string = "Hello, world!" index = my_string.find("hello") print(index) # Output: -1

In this example:

  • The search for "hello" (lowercase) returns -1 because it is not found in the original string.

Example 6: Multiple occurrences

# Example 6: Multiple occurrences my_string = "apple banana apple orange" index = my_string.find("apple") print(index) # Output: 0

Here:

  • The first occurrence of "apple" is found at index 0, even though there is a second occurrence later in the string.